Reputation: 3268
Note: I'd found out this open question What's the correct place to share application logic in CakePHP? which is very similar, but since the questions is open and dead since 2010 I think is better to create a new one.
I have some common functions that I'd like to use without reapeating them in several parts on my Cakephp app, concretely in Model and Controller. These functions are pretty simple, like reparsing a string to remove strange characters, so I can apply them in different points and I dont want to mantain several copies from same code.
The first thing I thougth was to use a Component but there is not recommended to use them in Models, I also see that is possible to use a plugin but I think is too much big to mantain.
Maybe I could just put these funcions in the bootstrap file, but I don't like so much this solution.
Which is the better way to achieve this logic sharing?
Upvotes: 1
Views: 636
Reputation: 498
Like Dave and burzum said, if it's related to data, put it in a Model/Behavior.
But if it's more general, you can simply put it in an external lib and then use this lib.
Lib/MyLib.php
<?php
class MyLib {
public static function doThis() {}
}
app/Controller/FooController.php
<?php
App::uses('AppController', 'Controller');
App::uses('MyLib', 'Lib');
class FooController extends AppController {
public function someAction () {
MyLib::doThis();
}
}
app/Model/Foo.php
<?php
App::uses('AppModel', 'Model');
App::uses('MyLib', 'Lib');
class Foo extends AppModel {
public function someMethod () {
MyLib::doThis();
}
}
Upvotes: 1
Reputation: 29121
Could put them in your AppModel. That way, you could access them from any Model (which means you could also access from any Controller).
If you put it in the AppModel, it will just automatically BE available to all models.
And you could access them via any controller by running it through a loaded model:
// in any Model
$this->whateverMethod();
// in any Controller
$this->MyModel->whateverMethod();
Upvotes: 0
Reputation: 25698
Rule of thumb: If it's data manipulation it should be done in a model.
If you want to share the logic between models: Make it behavior.
This way you can attach it to the models that need the functionality. In Cake3 you can use traits as well.
Upvotes: 1