Working with Namespaces
名前空間 は、クラス名の衝突を避けるために使用できます。つまり、もし同じクラス名を持つコントローラがアプリケーションに 2 つ存在する場合は、それらを区別するために名前空間を使用することができます。 名前空間はバンドルやモジュールの作成に役立ちます。
フレームワークの設定
Using namespaces has some implications when loading the appropriate controller. To adjust the framework behavior to namespaces is necessary to perform one or all of the following tasks:
Use an autoload strategy that takes into account the namespaces, for example with Phalcon\Loader:
<?php
$loader->registerNamespaces(
[
'Store\Admin\Controllers' => '../bundles/admin/controllers/',
'Store\Admin\Models' => '../bundles/admin/models/',
]
);
Specify it in the routes as a separate parameter in the route’s paths:
<?php
$router->add(
'/admin/users/my-profile',
[
'namespace' => 'Store\Admin',
'controller' => 'Users',
'action' => 'profile',
]
);
Passing it as part of the route:
<?php
$router->add(
'/:namespace/admin/users/my-profile',
[
'namespace' => 1,
'controller' => 'Users',
'action' => 'profile',
]
);
If you are only working with the same namespace for every controller in your application, then you can define a default namespace in the Dispatcher, by doing this, you don’t need to specify a full class name in the router path:
<?php
use Phalcon\Mvc\Dispatcher;
// Registering a dispatcher
$di->set(
'dispatcher',
function () {
$dispatcher = new Dispatcher();
$dispatcher->setDefaultNamespace(
'Store\Admin\Controllers'
);
return $dispatcher;
}
);
コントローラでの名前空間
The following example shows how to implement a controller that use namespaces:
<?php
namespace Store\Admin\Controllers;
use Phalcon\Mvc\Controller;
class UsersController extends Controller
{
public function indexAction()
{
}
public function profileAction()
{
}
}
モデルでの名前空間
Take the following into consideration when using models in namespaces:
<?php
namespace Store\Models;
use Phalcon\Mvc\Model;
class Robots extends Model
{
}
If models have relationships they must include the namespace too:
<?php
namespace Store\Models;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->hasMany(
'id',
'Store\Models\Parts',
'robots_id',
[
'alias' => 'parts',
]
);
}
}
In PHQL you must write the statements including namespaces:
<?php
$phql = 'SELECT r.* FROM Store\Models\Robots r JOIN Store\Models\Parts p';