Namespaces


Namespaces - 图1

Working with Namespaces

Namespaces can be used to avoid class name collisions; this means that if you have two controllers in an application with the same name, a namespace can be used to differentiate them. Namespaces are also useful for creating bundles or modules.

Setting up the framework

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:

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

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

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

Passing it as part of the route:

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

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:

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

Controllers in Namespaces

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

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

Models in Namespaces

Take the following into consideration when using models in namespaces:

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

If models have relationships they must include the namespace too:

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

In PHQL you must write the statements including namespaces:

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