Search code examples
phpperformancerequire-once

To require_once() or Not To require_once()


I am building a PHP CMS from the ground up. There is one super-core file within my system which I currently have automatically importing all other packages and classes that make up the core of the system. On a typical page, only a few of these classes and methods are used.

Considering the load require_once() puts on a server to include all of these files, and the time a user must wait for the page to load, I am wondering which path I should take:

  1. Keep the super-core as-is and automatically include all of the system core for each page that includes this core file.
  2. Use the super-core to include only essential packages, such as database management, and import additional packages/classes on an as-needed basis.

Could someone please let me know which of the two options are the best, as well as a brief overview of its pros and cons?

Thank you for your time!!!


Solution

  • Earlier this year, I came upon this exact problem while developing a framework in PHP.

    I considered the pros-cons and here's my evaluation:

    Option 1 - Front Controller Pattern script include all other scripts

    Advantages

    • Inclusion of packages are done within one script; you can see what files are included what are not at one glance.
    • Inclusion of a particular package is always called once, there is no overhead.

    Disadvantages

    • Consider the case of such:

    We have two classes Rectangle and Shape. Rectangle is a child class i.e. extension of Shape. However the core script includes the classes alphabetically. Thus when Rectangle is included, Shape is not found and PHP will throw an error.

    Rectangle class:

    class Rectangle extends Shape{
    
    }
    

    Shape class:

    class Shape{
    
    }
    
    • more overhead when everything that is not needed is also loaded into the memory.

    Option 2 - Load main packages, then load other packages as-needed

    Advantages

    • Files are only included when needed. Reduces overhead in another way
    • Solves the problem mentioned in Option 1.
    • You are able to concentrate on what each package requires from other packages and simply just load them

    Disadvantages

    • Overhead as multiple requests for a particular package may occur.
    • Package inclusion is done in every single file.

    Programming code is for human. Therefore to make things more logical and breaking down the problem, I chose option 2 to go for the framework.