Jump to content

Using namespace with autoloader


Go to solution Solved by requinix,

Recommended Posts

I haven't really been using namespace, and after reading PSR, I thought I should.  Some errors, however....

 

It is my understanding that the classes should be like the following two.  Correct?

<?php
namespace MyNameSpace;
class MyParentClass
{
    //....
}
namespace MyNameSpace;
class MyChildClass extends MyParentClass
{
    //....
}

To create an object, I would do??  When is use used?

  $pdo=new PDO(/*...*/);

  $myChild=new \MyNamespace\MyChildClass();

How should my autoloader be?

spl_autoload_register(function ($classname) {
    $parts = explode('\\', $classname);
    require "../classes/".end($parts).'.php';
    //require ("../classes/" . $classname . ".php");
});
Link to comment
https://forums.phpfreaks.com/topic/301959-using-namespace-with-autoloader/
Share on other sites

use (the one for namespaces) helps you not have to repeat fully-qualified names everywhere. That's really all it does.

 

I won't name names, but there are folks out there who write classes like

namespace Framework\Database\AbstractRecord\BaseClasses\TableBase;

abstract class DefaultTableBaseImplementation {
(there'd actually be an interface in there...)

 

To use that in your code you'd normally write

class MyDatabaseTable extends \Framework\Database\AbstractRecord\BaseClasses\TableBase\DefaultTableBaseImplementation {
That's rather unwieldy but acceptable on its own. Now imagine you have to reference a number of different classes. Say, traits:

class MyDatabaseTable extends \Framework\Database\AbstractRecord\BaseClasses\TableBase\DefaultTableBaseImplementation {

	use \Framework\Database\AbstractRecord\BaseTraitsThatEverybodyShouldUseToSaveTimeWritingCode\TableLowercaseNameTraitBase;
	use \Framework\Database\AbstractRecord\BaseTraitsThatEverybodyShouldUseToSaveTimeWritingCode\TableNoPrimaryKeyTraitBase;
	use \Framework\Database\AbstractRecord\BaseTraitsThatEverybodyShouldUseToSaveTimeWritingCode\TableIsViewTraitBase;
(which demonstrates a different use...)

 

Writing that all out every time sucks and encourages you to copy/paste code (something I hate). With a use statement you can

use \Framework\Database\AbstractRecord\BaseClasses\TableBase\DefaultTableBaseImplementation; // whole class
use \Framework\Database\AbstractRecord\BaseTraitsThatEverybodyShouldUseToSaveTimeWritingCode as FBaseTraits; // can have a shorter alias

class MyDatabaseTable extends DefaultTableBaseImplementation { // easier to read

	use FBaseTraits\TableLowercaseNameTraitBase;
	use FBaseTraits\TableNoPrimaryKeyTraitBase;
	use FBaseTraits\TableIsViewTraitBase;

Why does PHP think that PDO should be in the MyNameSpace namespace?  How do I prevent it from doing so?

<?php
namespace MyNameSpace;
class MyParentClass
{
    public function xyx()
    {
        // ...
        $bla=$stmt->fetch(PDO::FETCH_OBJ);
    }
}


 

  • Solution

Why does PHP think that PDO should be in the MyNameSpace namespace?  How do I prevent it from doing so?

PHP needs fully-qualified names to determine what classes are. If you write just "PDO" then PHP will think you want the PDO class in the current namespace; if you're not in a namespace then great, otherwise it won't find the class (unless you happen to have one with that name).

 

Write \PDO.

 

What about how to use spl_autoload_register

The class will be like "Path\To\Class"; the common answer is to convert backslashes to DIRECTORY_SEPARATORs and look for a matching filename.

spl_autoload_register(function($classname) {
	$path = str_replace("\\", DIRECTORY_SEPARATOR, $classname);
	require "/path/to/classes/{$path}.php";
});
But if that's all you need to do then you might as well use the built-in spl_autoload and put your /path/to/classes in the include path.

spl_autoload_register(); // equivalent to spl_autoload_register("spl_autoload")

Your autoloader ignores the entire namespace and only uses the class name. It will not be able to handle multiple classes with the same name but in different namespaces, like "Foo\Example" and "Bar\Example".

Thanks again Requinix,

 

I had previously tried \PDO but evidently did not do so on the script which was causing the error.  I take it I should use it everywhere such as \PDOException, right?  Also, even if I am not using namespace, I should do so, right?

 

Don't really see what the point of the below script is.  What is it doing?

 

The class will be like "Path\To\Class"; the common answer is to convert backslashes to DIRECTORY_SEPARATORs and look for a matching filename.

spl_autoload_register(function($classname) {
	$path = str_replace("\\", DIRECTORY_SEPARATOR, $classname);
	require "/path/to/classes/{$path}.php";
});

I take it I should use it everywhere such as \PDOException, right?

Right. You can't use something in the global namespace, but adding a backslash is easier anyways.

 

Also, even if I am not using namespace, I should do so, right?

Doesn't matter. Personally I wouldn't, simply because the code isn't using namespaces so I wouldn't "introduce" namespaces into it. But you can if you want. Consistency, maybe?

 

Don't really see what the point of the below script is.  What is it doing?

It's an autoloader for the most common class/file hierarchy: you have a file at /path/to/classes/Foo/Bar/Baz.php containing the class Foo\Bar\Baz. Nothing special with filenames, no sanity checks, just a simple class-to-path conversion method to find the right file.

 

But like I said, if you want to use that method then you should just use the built-in autoloading logic. Because it does the same thing.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.