|
| 1 | +.. index:: |
| 2 | + single: ClassLoader; PSR-4 Class Loader |
| 3 | + |
| 4 | +The PSR-4 Class Loader |
| 5 | +====================== |
| 6 | + |
| 7 | +.. versionadded:: 2.5 |
| 8 | + The :class:`Symfony\\Component\\ClassLoader\\Psr4ClassLoader` was |
| 9 | + introduced in Symfony 2.5. |
| 10 | + |
| 11 | +Libraries that follow the `PSR-4`_ standard can be loaded with the ``Psr4ClassLoader``. |
| 12 | + |
| 13 | +.. note:: |
| 14 | + |
| 15 | + If you manage your dependencies via Composer, you get a PSR-4 compatible |
| 16 | + autoloader out of the box. Use this loader in environments where Composer |
| 17 | + is not available. |
| 18 | + |
| 19 | +.. tip:: |
| 20 | + |
| 21 | + All Symfony components follow PSR-4. |
| 22 | + |
| 23 | +Usage |
| 24 | +----- |
| 25 | + |
| 26 | +The following example demonstrates how you can use the |
| 27 | +:class:`Symfony\\Component\\ClassLoader\\Psr4ClassLoader` autoloader to use |
| 28 | +Symfony's Yaml component. Imagine, you downloaded both the ClassLoader and |
| 29 | +Yaml component as ZIP packages and unpacked them to a ``libs`` directory. |
| 30 | +The directory structure will look like this: |
| 31 | + |
| 32 | +.. code-block:: text |
| 33 | +
|
| 34 | + libs/ |
| 35 | + ClassLoader/ |
| 36 | + Psr4ClassLoader.php |
| 37 | + ... |
| 38 | + Yaml/ |
| 39 | + Yaml.php |
| 40 | + ... |
| 41 | + config.yml |
| 42 | + demo.php |
| 43 | +
|
| 44 | +In ``demo.php`` you are going to parse the ``config.yml`` file. To do that, you |
| 45 | +first need to configure the ``Psr4ClassLoader``: |
| 46 | + |
| 47 | +.. code-block:: php |
| 48 | +
|
| 49 | + use Symfony\Component\ClassLoader\Psr4ClassLoader; |
| 50 | + use Symfony\Component\Yaml\Yaml; |
| 51 | +
|
| 52 | + require __DIR__.'/lib/ClassLoader/Psr4ClassLoader.php'; |
| 53 | +
|
| 54 | + $loader = new Psr4ClassLoader(); |
| 55 | + $loader->addPrefix('Symfony\\Component\\Yaml\\', __DIR__.'/lib/Yaml'); |
| 56 | + $loader->register(); |
| 57 | +
|
| 58 | + $data = Yaml::parse(__DIR__.'/config.yml'); |
| 59 | +
|
| 60 | +First of all, the class loader is loaded manually using a ``require`` |
| 61 | +statement, since there is no autoload mechanism yet. With the |
| 62 | +:method:`Symfony\Component\ClassLoader\Psr4ClassLoader::addPrefix` call, you |
| 63 | +tell the class loader where to look for classes with the |
| 64 | +``Symfony\Component\Yaml\`` namespace prefix. After registering the autoloader, |
| 65 | +the Yaml component is ready to be used. |
| 66 | + |
| 67 | +.. _PSR-4: http://www.php-fig.org/psr/psr-4/ |
0 commit comments