I’m building an application in CakePHP 3. It uses a number of legacy databases which are not built in the Cake conventions.
I do not want to use any of the ORM features Cake provides, as it’s more tedious to set up all the relations than just write “Raw SQL”. We are also not going to make any changes to the database structures, so the ORM is a non-starter. So I’m going to write raw SQL queries for everything.
However, I’m not sure where this code would be put. I’ve read https://book.cakephp.org/3.0/en/orm/database-basics.html#running-select-statements but it doesn’t say where you actually put that code.
I don’t want to put my queries in a controller ideally since that defeats the purpose of MVC.
All I really need is one Model where I can put all my queries in different functions and reference them in my Controller(s).
In Cake 2.x it was easy to just create a model under app/Model/
then load it (loadModel
) where needed in controller(s). But with the new Cake 3.x Table
and Entity
spaces, I’m not sure how this fits in?
I’ve also read up on Modelless Forms but don’t think they’re right either. For example the initial page of the application shows a list of chemicals which is just a SELECT
statement – it doesn’t involve forms or user input at all at this stage.
Obviously there will also be situations where I need to pass data from a Controller to the Model, e.g. queries based on user input.
Advertisement
Answer
As mentioned in the comments, I would suggest to not ditch the ORM, it has so many benefits, you’ll most probably regret it in the long run.
Setting up the tables shouldn’t be a big deal, you could bake everything, and do the refactoring with for example an IDE that does the dirty work of renaming references and filenames, and then set up the rules and associations manually, which might be a little tedious, but overally pretty simple, as there shouldn’t really be much more to configure with respect to the database schema, than the foreign keys, and possibly the association property names (which might require updating possible entities @property
annotations too) – maybe here and there also conditions and stuff, but oh well.
That being said, for the sake of completeness, you can always create any logic you want, anywhere you want. CakePHP is just PHP, so you could simply create a class somewhere in say the Model
namespace (which is a natural fit for model related logic), and use it like any other class wherever needed.
// src/Model/SomeModelRelatedClass.php namespace AppModel; class SomeModelRelatedClass { public function queryTheDatabase() { // ... } }
$inst = new AppModelSomeModelRelatedClass(); $results = $inst->queryTheDatabase();
See also