Question

I have create my own MVC framework which is PSR-0 compliant atm. and uses php-ActiveRecord as ORM. I have found an issue where I from a controller called User, which exists in the namespace TapMVC\Application, tries to call an ActiveRecord model ALSO called User but exists in the namespace TapMVC\Db like so:

namespace TapMVC\Application;

use TapMVC\Db;

class User extends Controller {
    function index() {
        print_r(Db\User::find('all'));
    }
}

This gives the following error:

Cannot redeclare class TapMVC\Application\User in /path/to/project/app/Controllers/user.php on line 12

Where line 12 is the prototype/declaration of the User-controller.

Why can't i do this? I thought that if your classes where i different namespaces and had a namespace prefix on instantiation it would be ok to have the same name? Also it looks like the data-model is declared before the controller through autoloading (since its the user-controller declaration which triggers the error), so why is there a conflict when the data-model is in namespace TapMVC\Db and not TapMVC\Application where the controllers are?

What i can see, that even though you define different namespaces, PHP will declare the object under the same namespace as the one in the active file, but i am not sure.

Hope someone can help so i dont need to name my data models like so: (ProjectName-prefix)User and edit the database tables in order to have a User-model and a User-controller.

Was it helpful?

Solution

I found the error! :-D

The issue lied in my autoloading functions for controllers, models etc. since i didn't take care of namespaces. So when I tried to load a controller or model named the same, the spl_autoload_register function would start off by checking for controllers, and since my functions ignored the classes namespaces it would i both cases of: TapMVC\Application\User and TapMVC\Db\User find the User-controller class, stop the autoload list, and try to declare it.

This all resolved when i took care of the namespaces and made sure that controllers/models only get loaded as long as they are in the correct namespace. If not the function dose nothing and the spl_autoload_register function continues down the list of autoload functions.

The question was more framework specific than imagined and boiled down to autoloading which i didn't think was the problem... for some reason, and for that i am sorry. Just happy know that I found the error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top