Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP namespace autoloading have to use folders?

I am quite confused in implementing namespace in php, especially when it comes to alias - importing classes.

I have followed the tutorial from this tutorial:

  • Leveraging PHP V5.3 namespaces for readable and maintainable code (by Don Denoncourt; 1 Mar 2011; for IBM Developerworks)

But I don't understand - when __autoload is used, why I have to store the alias classes in folders, but when __autoload is not used, the alias in namespace are just fine, like this below,

<?php
namespace barbarian;
class Conan {
    var $bodyBuild = "extremely muscular";
    var $birthDate = 'before history';
    var $skill = 'fighting';
}
namespace obrien;
class Conan {
    var $bodyBuild = "very skinny";
    var $birthDate = '1963';
    var $skill = 'comedy';
}
use \barbarian\Conan as mother;
$conan = new mother();
var_dump($conan);
var_dump($conan->bodyBuild);

$conan = new \obrien\Conan();
var_dump($conan);
var_dump($conan->birthDate);
?>

While this I will get error, if I don't store Conan.php in the folder of barbarian

<?php
require_once "autoload.php"; 
use \barbarian\Conan as Cimmerian;
$conan = new Cimmerian();
var_dump($conan);
?>

the error message,

Warning: require(barbarian/Conan.php): failed to open stream: No such file or directory in C:\wamp\www\test\2013\php\namepsace\autoload.php on line 12

The autoload.php:

<?php
function __autoload($classname) {
  $classname = ltrim($classname, '\\');
  $filename  = '';
  $namespace = '';
  if ($lastnspos = strripos($classname, '\\')) {
    $namespace = substr($classname, 0, $lastnspos);
    $classname = substr($classname, $lastnspos + 1);
    $filename  = str_replace('\\', '/', $namespace) . '/';
  }
  $filename .= str_replace('_', '/', $classname) . '.php';
  require $filename;
}
?>

Is it a must to store alias classes in folders? Is it possible to import the classes without storing them in folders when autoload is used?

like image 574
Run Avatar asked Mar 28 '13 17:03

Run


1 Answers

Autoloading classes with namespaces means it has to follow a convention, usually that convention involves using folders (compare with PSR-0).

If you have classes that sometimes follow that convention, then how would the autoloader know when to use folders or not?

So ultimately, yes classes should be stored in folders according to their namespaces. If you think the folder structure does not make sense, then you should change both namespaces and folder structure to reflect what you really want.

like image 84
Populus Avatar answered Sep 27 '22 02:09

Populus