I am using PHP ActiveRecord with my small MVC framework thtat includes an autoloader. In my controller I access the model Pub::find(64) for example.
My problem is that Pub::find(64) is inheritating the namespace of the controller and I get the error
Fatal error: Class 'App\Controllers\Pub' not found in /home/i554246/public_html/mvc/App/Controllers/Index.php on line 27
Pub is the Module name. The file get included ok. I can solve this issue by appending \Pub::find(64) but this is not really intuitive for new people on the project.
Is there a way to stop the namespace appending for the Pub::find(64) without altering that line?
Index Controller
namespace App\Controllers;
class Index extends \Core\Controller
{
protected
$title = 'Home'
;
/**
* Default action
*/
public function index()
{
// Pass the data to the view to display it
$this->view->set('testdb', \Pub::find(64));
}
}
App.php
/**
* Class autoloader
* @param $className
* @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
*/
public function autoload($className)
{
preg_match('/(^.+\\\)?([^\\\]+)$/', ltrim($className, '\\'), $match);
//Build namespace Autoloading
$file = str_replace('\\', '/', $match[1]) . str_replace('_', '/', $match[2]) . '.php';
//Build Model path
$model = 'App/Models/' . $match[2] . '.php';
if ( is_file($file) ) {
require $file;
}elseif ( is_file($model) ) {
require $model;
}
}
Models/Pub.php
class Pub extends ActiveRecord\Model
{
}
It seems you don't understand namespaces.
Since you are using namespace App\Controllers, the global namespace is denoted with \.
So if you don't want to use fully-qualified name \Pub you have to put use declaration below the namespace, eg:
namespace App\Controllers;
use Pub;
PS: It's a good practice to put your models in a namespace too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With