使用命名空间(Working with Namespaces)

Namespaces 可以用来避免类名的冲突,比如如果在一个应用中有两个控制器使用同样的名称,那么可以用namespace来区分他们。另外命名空间在创建组件或者模块的时候也是非常有用的。

设置框架(Setting up the framework)

Using namespaces has some implications when loading the appropriate controller. To adjust the framework behavior to namespaces is necessaryto perform one or all of the following tasks:

Use an autoload strategy that takes into account the namespaces, for example with Phalcon\Loader:

  1. <?php
  2.  
  3. $loader->registerNamespaces(
  4. array(
  5. "Store\\Admin\\Controllers" => "../bundles/admin/controllers/",
  6. "Store\\Admin\\Models" => "../bundles/admin/models/"
  7. )
  8. );

Specify it in the routes as a separate parameter in the route’s paths:

  1. <?php
  2.  
  3. $router->add(
  4. "/admin/users/my-profile",
  5. array(
  6. "namespace" => "Store\\Admin",
  7. "controller" => "Users",
  8. "action" => "profile"
  9. )
  10. );

Passing it as part of the route:

  1. <?php
  2.  
  3. $router->add(
  4. "/:namespace/admin/users/my-profile",
  5. array(
  6. "namespace" => 1,
  7. "controller" => "Users",
  8. "action" => "profile"
  9. )
  10. );

If you are only working with the same namespace for every controller in your application, then you can define a default namespacein the Dispatcher, by doing this, you don’t need to specify a full class name in the router path:

  1. <?php
  2.  
  3. use Phalcon\Mvc\Dispatcher;
  4.  
  5. // Registering a dispatcher
  6. $di->set('dispatcher', function () {
  7. $dispatcher = new Dispatcher();
  8. $dispatcher->setDefaultNamespace("Store\\Admin\\Controllers");
  9. return $dispatcher;
  10. });

控制器加入命名空间(Controllers in Namespaces)

The following example shows how to implement a controller that use namespaces:

  1. <?php
  2.  
  3. namespace Store\Admin\Controllers;
  4.  
  5. use Phalcon\Mvc\Controller;
  6.  
  7. class UsersController extends Controller
  8. {
  9. public function indexAction()
  10. {
  11.  
  12. }
  13.  
  14. public function profileAction()
  15. {
  16.  
  17. }
  18. }

模型加入命名空间(Models in Namespaces)

Take the following into consideration when using models in namespaces:

  1. <?php
  2.  
  3. namespace Store\Models;
  4.  
  5. use Phalcon\Mvc\Model;
  6.  
  7. class Robots extends Model
  8. {
  9.  
  10. }

If models have relationships they must include the namespace too:

  1. <?php
  2.  
  3. namespace Store\Models;
  4.  
  5. use Phalcon\Mvc\Model;
  6.  
  7. class Robots extends Model
  8. {
  9. public function initialize()
  10. {
  11. $this->hasMany(
  12. "id",
  13. "Store\\Models\\Parts",
  14. "robots_id",
  15. array(
  16. "alias" => "parts"
  17. )
  18. );
  19. }
  20. }

In PHQL you must write the statements including namespaces:

  1. <?php
  2.  
  3. $phql = 'SELECT r.* FROM Store\Models\Robots r JOIN Store\Models\Parts p';

原文: http://www.myleftstudio.com/reference/namespaces.html