Error Reporting Using Composer and Whoops

For this project, we will be using the Whoops library to handle errors. The Whoops library is a tool for examining errors that may occur in your projects. This library is packaged and made available for other developers to use in their projects.

Using Whoops, when an error occurs in PHP, you will be able to see this display information as opposed to standard bland error reporting from the server:

Error Reporting Using Composer and Whoops

Composer will manage the use of this dependency as it is considered among PHP developers a very widely used and a very popular package manager.

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. To install Composer, go to https://getcomposer.org/download/.

Imagine a scenario where you have to install a dependency for PHP, and for installing that dependency, you need to install other overhead dependencies. Composer helps you in handling this problem. It is used to handle all the work for you to install a library, as it downloads all the libraries and dependencies together.

Setting up Composer

We'll look at setting up Composer in this section. To do this, follow these steps:

  1. Create a folder to store the framework files.

    Note

    Feel free to call your folder anything you like, as long as it's all in lowercase without any spaces.

    • app holds the application files
    • system holds the core framework files
    • webroot will hold the publicly accessible files
  2. Next, we will set up Composer. Create a file in the root of your framework folder called composer.json.

    This file holds a JSON object that will autoload classes as we need them. We will be using PSR-4 autoloading.

    Note

    PSR-4 autoloading will load a class based on its namespace when it's being used. For instance, new AppModelsContact() will tell Composer to autoload a file called Contact that is stored in the folder appModels.

  3. Open composer.json and create an App and System definition.
  4. This will tell Composer that everything we call a namespace, with either App or System to look for the class in the app or system folders.
  5. We are also loading a third-party package called Whoops. We load this package by including it as a dependency in a require block:
    {
        "autoload": {
            "psr-4": {
                "App\" : "app/",
                "System\" : "system/"
            }
        },
        "require": {
            "filp/whoops": "^2.1"
        }
    }
  6. Save composer.json. Now, inside webroot, create two files: index.php and .htaccess.
  7. Open .htaccess.
  8. For security reasons, if a folder does not contain an index file, we don't want its contents displayed in a browser. To disable directory browsing, enter:
    Options –Indexes
  9. Next, a check is made to ensure mod rewrite is enabled:
    <IfModule mod_rewrite.c>
    //more code
    </IfModule>

    Note

    mod rewrite provides a rule-based rewriting engine to rewrite requested URLs on the fly. It helps to make URLs, so index.php?page can become /page.

  10. Next, turn on the rewriting engine and set the base to the root of this folder:
    RewriteEngine On
    RewriteBase /
  11. To force HTTPS, you can uncomment the # below, but only do this on a server that has HTTP enabled.
  12. Next, define the rewrite conditions.

    Note

    This is to ignore trailing slashes and folder and files that exist. Only dynamic files should be routed, for example, URLs that do not exist as physical files.

    The last rule passes all requests to index.php?$1. The $1 is the request after the first / in the requested URL.

    RewriteCond basically means "execute the next RewriteRule only if this is true".

    The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?$1, which means a request for contact will be rewritten as index.php?contact:

    RewriteRule ^(.*)$ index.php?$1 [QSA,L]

    QSA means that this flag forces the rewriting engine to append a query string part in the substitution string to the existing one instead of replacing it.

    The Secure Sockets Layer (SSL) creates an encrypted connection between your web server and your web browser. This stops any data being intercepted from your machine to the web server. It's recommended to use HTTPS.

    The complete file should look like this:

    # Disable directory snooping
    Options -Indexes
    
    <IfModule mod_rewrite.c>
    
        # Uncomment the rule below to force HTTPS (SSL)
    ………..
        RewriteRule ^(.*)$ index.php?$1 [QSA,L]
    </IfModule>

    Note

    For full code snippet, refer to Lesson 6.php file in the code files folder.

  13. Save the file. Now, open index.php.
  14. First, start php and then do a check to determine if vendor/autoload.php exists (it won't exist yet) and require the file.

    Note

    This is an important step. The autoload.php file will only exist once the Composer has been initialized. Checking before requiring the file is a precaution used to avoid a fatal error.

  15. We should inform the user what Composer is requesting and where to go and get it. We do this by using an else clause:
    if(file_exists('../vendor/autoload.php')){
        require '../vendor/autoload.php';
    } else {
        echo "<h1>Please install via composer.json</h1>";
        echo "<p>Install Composer instructions: <a href='https://getcomposer.org/doc/00-intro.md#globally'>https://getcomposer.org/doc/00-intro.md#globally</a></p>";
        echo "<p>Once composer is installed navigate to the working directory in your terminal/command prompt and enter 'composer install'</p>";
        exit;
    }
  16. Next, we will set our environment.
  17. We will define a constant called ENVIRONMENT and give it a value of development. When going into production, set the environment to production.

    Note

    When in production, you do not want to show errors. Having an environment constant is a good way to set what the environment of the application is:

    define('ENVIRONMENT', 'development');
  18. Now, based on the environment constant, we can set the appropriate level of error reporting:
    if (defined('ENVIRONMENT')){
        switch (ENVIRONMENT){
            case 'development':
                error_reporting(E_ALL);
            break;
            case 'production':
                error_reporting(0);
            break;
            default:
                exit('The application environment is not set correctly.');
        }
    }

    Note

    In development mode, all errors will be displayed, but in production, no errors will be displayed.

    The complete file looks like this:

    <?php
    if(file_exists('../vendor/autoload.php')){
        require '../vendor/autoload.php';
    } else {
    ……
                error_reporting(0);
            break;
    default:
                exit('The application environment is not set correctly.');
        }
    
    }

    Note

    For full code snippet, refer to Lesson 6.php file in the code files folder.

    Note

    A new folder will now have been created called vendor. This folder is where Composer installs its required files and any third-party dependencies.

  19. You can now go back to your browser and reload the page. You should now see a blank page.

    Note

    This means Composer is working, but we haven't yet requested anything to be loaded.

    Errors in view when the Whoops package is turned on will display the errors on the screen with a full stack trace of how the framework has executed the code along the way. This can help developers isolate the issue by following the path that their code has traveled on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset