I'm trying to inject a third-party authentication library into my Phalcon application. The file exists at /lib/Foo_Bar_AuthProvider.php:
<?php
namespace Foo\Bar;
class AuthProvider
{
public function authenticate()
{
return true;
}
}
I register this directory with the Phalcon autoloader in my bootstrapper, located at /public/index.php, and add it to the DI:
<?php
try {
//Register an autoloader
$loader = new \Phalcon\Loader();
$loader->registerDirs(array(
'../app/controllers/',
'../app/models/',
'../lib/'
))->register();
//Create a DI
$di = new \Phalcon\DI\FactoryDefault();
$di->set('authProvider', function() {
return new \Foo\Bar\AuthProvider();
});
// ...
}
Then I try to use this component in /app/controllers/AccountController.php:
<?php
class AccountController extends \Phalcon\Mvc\Controller
{
public function loginAction()
{
if (!$this->request->isPost()) {
return;
}
$success = $this->authProvider->authenticate();
if (!$success) {
$this->flash->error('Authentication failed.');
return;
}
$this->flash->success('Authentication succeeded. Welcome!');
return $this->dispatcher->forward(array('controller' => 'index', 'action' => 'index'));
}
}
This throws an exception:
Fatal error: Class 'Foo\Bar\AuthProvider' not found in /public/index.php on line 44
I am pretty new at using PHP namespaces so I'm probably missing something obvious, but I haven't been able to figure it out. I tried adding a backslash before the namespace declaration in Foo_Bar_AuthProvider.php like this:
namespace \Foo\Bar;
This didn't change anything. I also tried removing this backslash from the bootstrapper:
$di->set('authProvider', function() {
return new Foo\Bar\AuthProvider();
});
No dice here either. Finally, I tried adding the use statement to AccountController.php:
use \Foo\Bar;
Also:
use Foo\Bar;
I believe the purpose of the autoloader is to avoid such things, but adding the use statements didn't work anyways.