Skip to content

Commit 17166bd

Browse files
committed
First shot of a documentation of the new PSR-4 class loader.
1 parent 739f43f commit 17166bd

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

components/class_loader/index.rst

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ ClassLoader
66

77
introduction
88
class_loader
9+
psr4_class_loader
910
map_class_loader
1011
cache_class_loader
1112
debug_class_loader
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
.. index::
2+
single: ClassLoader; PSR-4 Class Loader
3+
4+
The PSR-4 Class Loader
5+
======================
6+
7+
Libraries that follow the `PSR-4`_ standard can be loaded with the ``Psr4ClassLoader``.
8+
9+
.. note::
10+
11+
If you manage your dependencies via Composer, you get a PSR-4 compatible
12+
autoloader out of the box. Use this loader in environments where Composer
13+
is not available.
14+
15+
.. tip::
16+
All Symfony Components follow PSR-4.
17+
18+
Usage
19+
-----
20+
21+
The following example demonstrates, how you can use the
22+
:class:`Symfony\\Component\\ClassLoader\\Psr4ClassLoader` autoloader to use
23+
Symfony's Yaml component. Let's imagine, you downloaded both components –
24+
ClassLoader and Yaml – as ZIP packages and unpacked them to a libs directory.
25+
26+
The directory structure will look like this:
27+
28+
.. code-block:: text
29+
30+
/
31+
+- libs
32+
| +- ClassLoader
33+
| | +- Psr4ClassLoader.php
34+
| | +- …
35+
| +- Yaml
36+
| +- Yaml.php
37+
| +- …
38+
+- config.yml
39+
+- test.php
40+
41+
In ``demo.php``, to parse the file ``config.yml``, you can use the following
42+
code.
43+
44+
.. code-block:: php
45+
46+
use Symfony\Component\ClassLoader\Psr4ClassLoader;
47+
use Symfony\Component\Yaml\Yaml;
48+
49+
require __DIR__ . '/lib/ClassLoader/Psr4ClassLoader.php';
50+
51+
$loader = new Psr4ClassLoader();
52+
$loader->addPrefix('Symfony\\Component\\Yaml\\', __DIR__ . '/lib/Yaml');
53+
$loader->register();
54+
55+
$data = Yaml::parse(__DIR__ . '/demo.yml');
56+
57+
First of all, we've loaded our class loader manually using ``require`` since we
58+
don't have an autoload mechanism, yet. With the ``addPrefix()`` call, we told
59+
the class loader where to look for classes with the namespace prefix
60+
``Symfony\Component\Yaml\``. After registering the autoloader, the Yaml
61+
component is ready to use.
62+
63+
.. _PSR-4: http://www.php-fig.org/psr/psr-4/

0 commit comments

Comments
 (0)