Organizing Controllers, Tables, and Entities in CakePHP 3 with Namespaces

Organizing Controllers, Tables, and Entities in CakePHP 3 with Namespaces

Takahiro Iwasa
Takahiro Iwasa
2 min read
CakePHP

Introduction

Applications can be better structured by organizing Controllers, Tables, and Entities using namespaces in CakePHP 3. This post explains how to implement namespaces for various components of your application.

Using Namespaces for Controllers

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

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

Using Namespaces for Tables

Registering Tables with TableRegistry

When using TableRegistry::get(), ensure you provide the fully qualified name, including ...Table.

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

Initializing a Table

By default, the alias for a Table is its fully qualified name. To override this, use the initialize() method.

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

Defining Associations

When defining associations such as belongsTo, hasOne, hasMany, or belongsToMany, specify the fully qualified name for className, including ...Table.

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

Using Namespaces for Entities

To specify an Entity class, use the Table->entityClass() method. Provide the fully qualified name as the argument.

$this->entityClass('App\Model\Entity\<NAMESPACE>\Employee');

Conclusion

Organizing your CakePHP 3 application using namespaces enhances code structure and scalability, especially in large applications. Proper use of namespaces for Controllers, Tables, and Entities simplifies maintenance and ensures a clean, modular design.

Happy Coding! 🚀

Takahiro Iwasa

Takahiro Iwasa

Software Developer at KAKEHASHI Inc.
Involved in the requirements definition, design, and development of cloud-native applications using AWS. Now, building a new prescription data collection platform at KAKEHASHI Inc. Japan AWS Top Engineers 2020-2023.