Skip to content

Latest commit

 

History

History
107 lines (78 loc) · 2.77 KB

9.md

File metadata and controls

107 lines (78 loc) · 2.77 KB

Lesson 9: Namespaces and autoloading

New Keywords:

  • namespace
  • use
  • use ... as

Namespaces

Namespaces are a way to encapsulate code, such that to access it, you must first declare which namespace you are referring. In practical terms, what this means is that adding a namespace to a class is very much like organizing classes into hierarchical directories.

The advantages of doing this is to keep things logically organized, and avoid name collisions with other libraries.

<?php

namespace ChapterThree\OOTraining;

class Person {
  ... // Class definition.
}

Note: Namespaces can be applied to classes, interfaces, and other similar structures as well.

To reference a namespaced class (for example, the class Symfony\Component\Yaml\Yaml), you can reference it by it's fully qualified name:

<?php

namespace ChapterThree\OOTraining;

class Person {
  public function __construct($filename) {
    $array = \Symfony\Component\Yaml::parse(file_get_contents($filename));
    // ... Do something else.
  }
}

Or by declaring the use keyword and adding the namespace to the top of the class:

<?php

namespace ChapterThree\OOTraining;

use Symfony\Component\Yaml;

class Person {
  public function __construct($filename) {
    $array = Yaml::parse(file_get_contents($filename));
    // ... Do something else.
  }
}

Use as

You can also create aliases to refer to the classes using as:

<?php

namespace ChapterThree\OOTraining;

use Symfony\Component\HttpKernel as Kernel;

class Person {
  public function __construct($filename) {
    Kernel::terminate();
  }
}

Autoloading

Once classes have been organized into namespaces, PHP can take advantage and autoload them whenever needed. PSR-4 describes a specification for autoloading classes from file paths, and is used by popular projects such as Symfony and Composer.

In Drupal 8, modules follow a PSR-4 directory structure, where each module has a namespace that under the "Drupal" parent namespace, and is mapped to "src/":

modules/chapterthree/
    src/
        Controller/
            PersonController.php  (class Drupal\chapterthree\Controller\PersonController)
        Form/
            PersonForm.php (class Drupal\chapterthree\Form\PersonForm)
        Entity/
            Person.php (class Drupal\chapterthree\Entity\Person)
    chapterthree.info.yml
    chapterthree.routing.yml
    chapterthree.module

Exercise:

  • Add a namespace to the top of your file, this will put all classes defined in that file into that namespace.
  • Add a constant or static variable to one of your classes / interfaces.
  • Print the constant/static by calling the full namespace of your class.
  • Add a use statement, and print your constant/static again using the short namespace of your class.