PSR-4 and Laravel

If you didn’t already know, psr-* is a php standard for auto-loading classes, it stands for PHP Specification Request, psr-4 is the latest version.

PSR-4 offers great flexibility, you can define namespaces with any location, for example we might use Acme namespace that looks for classes in a folder called app/BusinessLogic/ and later on, if you want to change the location you just change the location where you declare the namspace(composer.json) without touching any of you files.

PSR-4 namespace(s) can be defined within composer.json in autoload section:


"autoload": {
		"classmap": [
			"app/database/migrations",
			"app/database/seeds"
		],

        "psr-4": {
            "Acme\\": "app/BusinessLogic/",

        }
},

Note: “\\” is required at the end.

Let’s say we have class A inside BusinessLogic/, we will define Acme namespace and access the class like this:


new Acme\A();
Advertisements

One thought on “PSR-4 and Laravel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s