Skip to content

Latest commit

 

History

History
82 lines (60 loc) · 1.99 KB

7.md

File metadata and controls

82 lines (60 loc) · 1.99 KB

#Lesson 7: Namespaces and autoloading

##New Keywords:

  • namespace
  • use

##Namespaces

Namespaces are a way to encapsulate code, such that to access it, you must first declare to 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: Symfony\Component\Yaml\Yaml

<?php

namespace ChapterThree\OOTraining;

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

Or:

<?php

namespace ChapterThree\OOTraining;

use Symfony\Component\Yaml\Yaml;

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

##Autoloading

Once classes have been organized into namespaces, PHP can take advantage to 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