Tuesday 16 July 2019

PHP Autoload && namespace

If you need to order your code into namespaces, just use the keyword namespace:
file1.php
namespace foo\bar;
In file2.php
$obj = new \foo\bar\myObj();
You can also use use. If in file2 you put
use foo\bar as mypath;
you need to use mypath instead of bar anywhere in the file:
$obj  = new mypath\myObj();
Using use foo\bar; is equal to use foo\bar as bar;.







The simplest way is to autoload each class separately. For this purpose, all we need to do is define the array of paths to the classes that we want to autoload in the composer.json file.
For example:
 1 2 3 4 5 6 7 8{
  "autoload": {
    "classmap": [
      "path/to/FirstClass.php",
      "path/to/SecondClass.php"
    ]
  }
}
Update the composer autoloader from the command line:
$ composer dump-autoload -o
Now, we have to include the autoloader at the top of our scripts (e.g., index.php):
 1 2<?php
require "vendor/autoload.php";
In the same way that we autoload classes, we can autoload directories that contain classes also by using the classmapkey of the autoload:
 1 2 3 4 5 6 7 8{
  "autoload": {
    "classmap": [
      "path/to/FirstClass.php",
      "path/to/directory"
    ]
  }
}
  • In order to autoload directories we need to use namespaces.
As we can see, classmap autoloading is not much different than the long list of requires that we used to use in the older PHP scripts. Yet, the better way to autoload is by using the PSR-4 standard.

https://phpenthusiast.com/blog/how-to-autoload-with-composer

No comments:

Post a Comment