Search code examples
phpcakephpcode-reuse

How to write a reusable code in cakePHP?


Can any one provide me some tips to write reusable code in PHP / CakePHP?


Solution

  • [how to] write a single [delete] function in AppController

    Okay, I'll bite. You'd code it almost exactly as you would code it in the individual controllers, you just need to replace the parts that vary with variables.

    class AppController extends Controller {
    
        var $components = array('Session');
    
        function delete($id) {
            $model = $this->modelClass;  // holds the primary model name
            if (!$this->$model->delete($id)) {
                $this->Session->setFlash("Couldn't delete $model record $id.");
            }
            $this->redirect($this->referer());
        }
    }
    

    Read through Cake's source code to learn what variables are there for you to use. Read through more source code, especially of Components and Behaviors, which by definition are reusable, to learn more specific techniques.