Namespace for Controller, Table, Entity in CakePHP 3
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');
Conclusion
When handling large sized applications, it will be better to structure your code using namespace.
I hope you will find this post useful.