kla/php-activerecord — pull request #294 by brianmuse (2013-04-18 20:50:12+00:00)
Title: Avoid "Cannot Redeclare Class" error in autoloader when using namespaced models

Fixes issue #270, (cc #271)

After digging pretty deep, we found out that the autoloader was being called when it probably should not have been. It relates to how relationships are built when the model directory is set and models also use namespaces.

Let's say I load a model as follows:
```php
use \Models\User
```

ActiveRecord's autoloader will properly handle this and PHP will not attempt to reload this class in the future. However when creating relationships, an attempt is first made to create a ReflectionClass with non-namespaced version of a class (eg `User`). Currently if this fails, an exception is thrown and it will try again using the namespaced version.

Let's say that `$cfg->set_model_directory('Models');` has been executed during initialization of ActiveRecord.

When it attempts to use the non-namespaced version for the `ReflectionClass`, PHP treats `\User` as a never-seen-before class and will fire the ActiveRecord autoloader method. Because of the way ActiveRecord's autoloader is designed, it will attempt to pre-pend the model directory to the class name and attempt to load a file that has already been loaded.

So there are two issues (in a sense). `set_model_directory` should not be used if models are namespaced. This is a usage error that the library could handle this more gracefully if it prioritized loading based on namespace (if it exists) and then falls back to the global namespace.

The other concern with `set_class_name` first using the non-namespaced name of a class is that the ReflectionClass and autoloader might use/load the wrong class entirely. (If we've defined `\User` and `\Models\User` as separate classes.)