PSR-0, PSR-4 & xAutoload

Why autoload?

  1. We don't want including file before use class
  2. We don't want waste time to find where the class is stored in.
  3. We are lazy

Why PSR-0

  • Every library include their own autoloading magic
  • Don't repeat yourself
  • I want autoload, which library is built for me?

PSR-0: Mapping

# Mapping:
# -------

MasterNamespace           ----> /path/to/lib-root/

# Finding:
# -------

MasterNamespace\ClassName 
  --> /path/to/lib-root/MasterNamespace/ClassName.php

# Backward compatible:
# -------

MasterNamespace_ClassName 
  --> /path/to/lib-root/MasterNamespace/ClassName.php

Simple convention

Work for all

But…

# Mapping
# -------
CompanyName --> /path/to/company_name/project_name/foo/
CompanyName --> /path/to/company_name/project_name/bar/

# Finding
# -------
CompanyName\ProjectName\Foo\ClassName -> /path/to/company_name/project_name/foo/CompanyName/ProjectName/Foo/ClassName.php
CompanyName\ProjectName\Bar\ClassName -> /path/to/company_name/project_name/bar/CompanyName/ProjectName/Acme/Foo/ClassName.php

# Problem: yeah, something wrong!
# -------

PSR-4

  • A better PSR-0

  • But breaks backward compatibility

PSR-4: Just got better

// Mapping
CompanyName\Project --> /path/to/root/


// Finding
CompanyName\Project\Foo\ClassName
    --> /path/to/root/Foo/ClassName.php

xautoload.module

Modern autoloading for Drupal 7

my_module.info

name = My modern module

version = 7.x-1.0-dev

core = 7.x

 

dependencies[] = xautoload

 

{module root}/

/src/PSR4Demo.php

/lib/Drupal/my_module/PSR0Demo.php

 

<?php

function excited() {
  $p0  = new Drupal\my_module\PSR0Demo();
  $p4 = new Drupal\my_module\PSR4Demo();
}
Made with Slides.com