I am writing a very general script for data manipulation. For this I need to know the table name associated to the current controller. Somehow I cannot figure out how to get it.
UPDATE
Usually, each Controller has in the template/<name>
directory the following PHP files:
add.php
edit.php
index.php
view.php
This means that for 20 tables I have to maintain 80 files and this is really stupid. Therefore I am using the CRUD plugin which minimizes it significantly and now I have only one my_index.php
which covers the 20 physically versions of index.php
for all affected tables.
In order to generate a proper view for each table I need the table’s schema and for this I need to know the table name.
Therefore:
Any solution which adds a code into the proper Controller is not a solution as I have to touch/maintain again 20 files with the same line of code and this is definitely not the DRY concept. The solution must be something where I have the code ONCE in my_index.php
.
What is the code to get the current table name?
I can run this code as described here https://book.cakephp.org/4/en/orm/table-objects.html#getting-instances-of-a-table-class but this has to be ran in each controller and it violates a bit the DRY concept as I have to add it manually into each controller… I am looking for a more general method.
I am running CakePHP Strawberry 4.1.
4
Answers
After playing around I found this solution:
I have to place this code ONCE in
my_index.php
and I am done.I don't think this is an optimal solution as I have to create a dummy instance of the controller from which I want to get the table name.
Any better solution is more than welcome and accepted.
The default table short class name is derived from the controller name, and the possible plugin name, and it is being stored in the
$modelClass
property ofCakeDatasourceModelAwareTrait
that the controller inherits.In a controller named
ArticlesController
, the$this->modelClass
proeprty will holdArticles
, and if the controller would live in a plugin namedBlog
, the property would holdBlog.Articles
.Your controller(s) should extend
AppController
. If you need the schema in the view, thenAppController::beforeFilter
can do all of the work required to find it, right in the controller, and set that as a $schema variable that your view can use. Something like this (untested, but should be quite close):You need only define controller property