Skip to content

Specific table aware TableLocator #18954

@Harfusha

Description

@Harfusha

Description

Hello, i use TableRegistry::getTableLocator()->get(...) everywhere in my system. If i want to have specific table for PHPStan and autocomplete i needed to use assert under every ->get().

All i did is this:

final class TypedTableLocator extends TableLocator {
    /**
     * Get a table instance with generic type inference.
     *
     * @template T of \Cake\ORM\Table
     * @param class-string<T> $className
     * @return T
     */
    public function getAware(string $className): Table {
        /** @var T $table */
        $table = $this->get($className);
        return $table;
    }
}

$Admins = CustomTableRegistry::getTableLocator()->getAware(AdminsTable::class);
debug($Admins); // Linter and PHPStan shows \App\Model\Table\AdminsTable
$Admins = CustomTableRegistry::getTableLocator()->getAware('Admins');
debug($Admins); // Linter and PHPStan shows \Cake\ORM\Table
$NonExisting = CustomTableRegistry::getTableLocator()->getAware('NonExisting');
debug($NonExisting); // Linter and PHPStan shows \Cake\ORM\Table

CakePHP Version

4.6.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions