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?
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();
}
}