cakephp $uses or request action - php

i am in a situation where i need to fetch data from 6 models. i can't use associations as they are not related. So what should i use $uses or request action or any other solution

I'd recommend you to use
ClassRegistry::init("model_name")
or
loadModel("model_name")
instead.
E.g.
To use a User model
$this->User = ClassRegistry::init('User');
Or
$this->loadModel('User');
Then you can do some query like
$this->User->find("all");

If you are going to need those models for only one find call with associtaions needed, I recommend using bindModel, see Creating-and-Destroying-Associations-on-the-Fly.

I disagree with Travis. It is much better to use loadModel then you can be sure you're loading what you need when you need it. Who's to say you won't extend the model to include methods that don't require all those other models?
Cut and paste is a big boost to programmer performance.

You could try $uses, or, if you want to only load the models when and where you need them, you could use loadModel (http://book.cakephp.org/view/845/loadModel). LoadModel is better that $uses, performance wise.

As others recommended, you should use Controller::loadModel().
Additionaly, I'd suggest you make something like YourController::_loadMyMegaData() which would load all the necessary models and set your data. This will avoid loading those models by accident and spare you any if blocks later on.
Also, avoid requestAction() whenever possible, it's not only ugly, you also take a performance hit. (It has it's use of course, but that doesn't happen very often:))

You can use the following:
$this->loadModel('ModelName');
$this->ModelName->find();
If you are retrieving only single field than you can use virtual fields

Related

Should we use 'use' if we only call a function once?

Is it bad to use the keyword use even though we only call a function once?
E.g. I have my own typo3 extension, and I am accessing a typo3 core function in my controller, but only once.
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
I could also make use of use:
use \TYPO3\CMS\Core\Utility\GeneralUtility;
...
$message = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
In my opinion the second variant is much cleaner, but are there any performance issues if I make use of use only for one call?
In theory, there should be no performance hit. You're calling a function (and thus an autoloader) either way (which is where any performance hit will be).
To explain why, your use statement is simply an alias. Your autoloader will do the same work either way. And it will likely be opcode cached, so any performance hit (we're talking milliseconds here, if that) will only be on the first run.
It's much cleaner to import the classes and then use ::class to reference them e.g...
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Mail\MailMessage;
$message = GeneralUtility::makeInstance(MailMessage::class);
I particularly prefer the second choice too. And there is no performance hit. You can use the second one without any concern.
First option is faster when in namespace context and it could be more readable because of FQNS (it's a matter of taste). When there is a lot of "imports"
it may indicate too high a degree of dependence and break of the single responsibility principle. So I often use inline namespacing using FQNS.
Optimizing PHP performance by using fully-qualified function calls
https://veewee.github.io/blog/optimizing-php-performance-by-fq-function-calls/
Try to profile your code to get the answer.

Is there a convention for naming Controller functions?

In MVC, some controller functions require accessing the model before rendering a view, whereas others simply load the view.
In a blogging app, I have two functions:
public function add_post()
{
// loads the view for adding a new post
}
public function add_new_post()
{
// queries database and inserts post
}
I'm used to using Java, where all methods have a highly suggestive verb that describes what the method is supposed to do. So, instead of add_post(), I would use add_post_view(), and instead of add_new_post(), I would be able to use add_post().
But I'm afraid that adding "view" at the end seem redundant - but aside from that, I'd like to know what the convention is for those who like to have highly readable code. How would you go about rewriting the names of these two functions?
For php, in general, there is no specialized naming convention or should I rather say standardized. Working for several companies over the years I have seen it all from thisismyfunction to thisIsMyFunction to this_is_my_function..
My personal choice though, is if its internal functionality (models or controllers alike) that aren't AJAX ready I tend to use the underscore method with a couple comments under or above each function to give me an idea. But for functions I intend to use with AJAX such as in a controller I will usually go the camel-case route. Generally speaking its all about preference on your side of it. If your more comfortable with underscore use that, if not then use camel case, or whatever suits ya.
If this is going to be a team project, or potentially a project where either a team will come aboard, or where you expect to be bought out. I'd say go for what ever is easiest learning curve wise, last thing you want to do is bring others in or sell a product that your going to have to spend long times training people how to read through your code. Rather than collect and go, or just have them start building away.
Its good practice to use 'thin' controllers, i.e. not to add too many methods on any single controller. With that in mind, I usually have a well named controller with only one (two max) public methods on there. Usually corresponding to GET and POST.

Add INSERT IGNORE Statement to CAKEPHP saveAll method

I need to add IGNORE option to saveAll() method in CAKEPHP. I want exact impementation of this . Some other SO questions answered related to validations and isUnique() checking like that. I need to implement this conditions , don't care waht is going on behind .
Please advise me.
The only way that I think this would be possible, other than using the execute() function provide by your data source is if you extended the Mysql datasource class and changed the behaviour of the create() and renderStatement() functions to includes case where you want it to append the IGNORE SQL keyword.
You'd want to place the data source file in APP/Model/Datasource/ and have it extends Mysql (assuming you use CakePHP 2+). Have a look at the 2 functions above. I'd just create a case where if uses 'createignore' instead of 'create' when calling renderStatement() when a certain option is passed to create().
That said, there most likely is a way to achieve what you're trying to do without going through that much trouble. If you elaborate on what you're trying to do, I might be able to give you a better answer.

Function vs Objects Best Practice

I am wondering whats the best practices regarding functions and objects. For example I want to perform an action called tidy. It will take my data as input and tidy it and return it.
Now I can do this in two ways. One using a simple function and the other using a class.
Function: $data = tidy($data);
Class:
$tidy = new Tidy();
$data = $tidy->clean($tidy);
Now the advantage in making it a class is that I do not have to load the class before. I can simply use the autoload feature of php to do so.
Another example is the database class. Now everyone seems to be using a separate class for db connectivity. But we usually have a single object of that class only. Isn't this kind of contrary to the definition of class and objects in a sense that we are using the class only to intantiate a single object?
I kind of dont understand when to use a function and when to use a class. What is the best practice regarding the same? Any guidelines?
Thank you,
Alec
For something that does one thing, and only one thing, I'd just use a function. Anything more complex, and I'd consider using an object.
I took the time to poke through some piles of (arguably ugly and horrible) PHP code and, really, some things could have been done as objects, but were left as functions. Time conversions and string replacements.
Functions typically do one specific task.
Objects represent something that have tasks associated with it. (methods)
Use a function for tidy. Plain and simple. ;-)
I'd personally make a 'data' object that handles data then have a tidy method under it.
This pattern will allow the number of tasks you do on data to expand while containing it all in a nice little self-contained chunk.
For your case, I'd make it a function, possibly a static function in something like a "util" class (for which the only purpose of the class is to act like a namespace - it'll group all your random useful methods together). As a rule of thumb, only use an object if it needs to store some data that needs to live between multiple function calls. That's why the database methods are made to be part of an object, because they store a database handle which is used between multiple function calls. Yes, there only ever is one database object, but having it as an object groups all the database-related stuff into one place, making it easier to maintain and keep bug-free.

In CodeIgniter is It OK to use `$this->load->model( )` as Often as Needed?

I have lots of code in models, and although the model might be loaded elsewhere, I like to make sure by doing $this->load->model() almost everywhere its used. Is that all right, or does it use up any resources; even if the model has already been loaded?
The constructor will be executed every time you call $this->load->model(), but the file itself will be loaded only once. It might make sense to put your often-used model into application/config/autoload.php
Its better to load the model in the constructor.so tat no need to repeat the code again and again..

Categories