Namespace for Controller, Table, Entity in CakePHP 3

Namespace for Controller, Table, Entity in CakePHP 3

Takahiro Iwasa
(岩佐 孝浩)
Takahiro Iwasa (岩佐 孝浩)
1 min read
CakePHP

Applications can be better structured by separating Controllers and Models (Tables/Entities) in CakePHP 3 using namespaces.

Controller

To add a namespace to prefix in routes.php, use App\Controller\<NAMESPACE> format.

$routes->connect('/employees', [
    'prefix'     => '<NAMESPACE>',
    'controller' => 'Employees',
    'action'     => 'index',
    '_method'    => ['GET'],
    '_ext'       => 'json',
]);

Table

TableRegistry::get()

When specifying the argument for TableRegistry::get, be sure to provide the fully qualified name, including the ...Table.

$table = TableRegistry::get('App\Model\Table\<NAMESPACE>\EmployeesTable');

Table->initialize()

By default, an alias for a Table is the fully qualified name. If you do not want to use the fully qualified name as the alias, you can override initialize() method.

public function initialize(array $config)
{
    parent::initialize($config);
    $this->alias('Employees');
}

Association definition

When defining associations using belongsTo, hasOne, hasMany, or belongsToMany, be sure to specify the fully qualified name for className, including the ...Table.

$this->belongsTo('Estimates', [
    'className'    => 'App\Model\Table\<NAMESPACE>\CompaniesTable',
    'propertyName' => 'company',
]);

Entity

You can use Table->entityClass() to specify an Entity class. When specifying the argument for Table->entityClass(), be sure to provide the fully qualified name.

$this->entityClass('App\Model\Entity\<NAMESPACE>\Employee');
Takahiro Iwasa
(岩佐 孝浩)

Takahiro Iwasa (岩佐 孝浩)

Software Developer at iret, Inc.
Architecting and developing cloud native applications mainly with AWS. Japan AWS Top Engineers 2020-2023