发布于 2015-08-21 15:13:04 | 495 次阅读 | 评论: 0 | 来源: 网络整理
Namespaces 可以用来避免类名的冲突,比如如果在一个应用中有两个控制器使用同样的名称,那么可以用namespace来区分他们。 另外命名空间在创建组件或者模块的时候也是非常有用的。
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 PhalconLoader:
<?php
$loader->registerNamespaces(
array(
"StoreAdminControllers" => "../bundles/admin/controllers/",
"StoreAdminModels" => "../bundles/admin/models/"
)
);
Specify it in the routes as a separate parameter in the route’s paths:
<?php
$router->add(
"/admin/users/my-profile",
array(
"namespace" => "StoreAdmin",
"controller" => "Users",
"action" => "profile"
)
);
Passing it as part of the route:
<?php
$router->add(
"/:namespace/admin/users/my-profile",
array(
"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 PhalconMvcDispatcher;
// Registering a dispatcher
$di->set('dispatcher', function () {
$dispatcher = new Dispatcher();
$dispatcher->setDefaultNamespace("StoreAdminControllers");
return $dispatcher;
});
The following example shows how to implement a controller that use namespaces:
<?php
namespace StoreAdminControllers;
use PhalconMvcController;
class UsersController extends Controller
{
public function indexAction()
{
}
public function profileAction()
{
}
}
Take the following into consideration when using models in namespaces:
<?php
namespace StoreModels;
use PhalconMvcModel;
class Robots extends Model
{
}
If models have relationships they must include the namespace too:
<?php
namespace StoreModels;
use PhalconMvcModel;
class Robots extends Model
{
public function initialize()
{
$this->hasMany(
"id",
"StoreModelsParts",
"robots_id",
array(
"alias" => "parts"
)
);
}
}
In PHQL you must write the statements including namespaces:
<?php
$phql = 'SELECT r.* FROM StoreModelsRobots r JOIN StoreModelsParts p';