Drupal8: In with PSR-4, Out with PSR-0

php-med-trans-lightA significant change is coming down the pipe for Drupal 8 development. PSR-4 support is here! In the long term it will be the defacto standard for autoloading classes from file paths in Drupal 8. Prior to this Changeset Notification Drupal 8 supported PSR-0 autoloading.

PSR-4 is the 4th PHP Standards Recommendation from the PHP Framework Interop Group (FIG). PHP-FIG seeks to be a cross-section of PHP developer ecosystem all weighing in their thoughts and best practices as Standards adoptable by the whole PHP community at large.

What does PSR-4 mean for your Drupal 8 coding endeavors, well let’s take a look at a sample directory structure of a module:

Before (PSR-0)

/modules/my_module/my_module.info.yml
/modules/my_module/lib/Drupal/my_module/MyModuleClass.php
/modules/my_module/lib/Drupal/my_module/Entity/MyEntity.php # Plugin
/modules/my_module/lib/Drupal/my_module/Tests/MyEntityTest.php # Simpletest
/modules/my_module/tests/Drupal/my_module/Tests/Entity/MyEntityTest.php # PHPUnit

After (PSR-4)

/modules/my_module/my_module.info.yml
/modules/my_module/src/MyModuleClass.php
/modules/my_module/src/Entity/MyEntity.php # Plugin
/modules/my_module/src/Tests/MyEntityTest.php # Simpletest
/modules/my_module/tests/src/Entity/MyEntityTest.php # PHPUnit

Basically, autoloaded classes are moved directly into the ./src subdirectory. This applies to all classes in your namespace. Classes in sub-namespaces are retained in subdirectories as-is.

For the meantime while Drupal 8 is in development PSR-0 and PSR-4 support will exist in Core for a brief period. But, in the long term PSR-0 will be phased out and PSR-4 is to be the standard. If you want to keep track of how long you may have PSR-0 code laying around track this issue #2247287: [PP-2] Drop automatic PSR-0 support for modules.

It’s great to see Drupal moving forward!

Looking for quality web hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , , | Posted under Drupal | RSS 2.0

Author Spotlight

David Gurba

David Gurba

I am a web programmer currently employed at UCSB. I have been developing web applications professionally for 8+ years now. For the last 5 years I’ve been actively developing websites primarily in PHP using Drupal. I have experience using LAMP and developing data driven websites for clients in aviation, higher education and e-commerce. If you’d like to contact me I can be reached at david.gurba@arvixe.com

Leave a Reply

Your email address will not be published. Required fields are marked *


× 2 = 14

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>