About code reuse

Hello everyone:

I’m developing a application for website and mobile app; I have created a controller:

namespace App\Controller

class OrdersController extends AppController
{
    function placeOrder()
    {
         //generate order business
        return $this->response();
    }
}

Now I need to create a api controller

namspace App\Api\Controller;

class OrdersController extends AppController
{
    function placeOrder()
    {
         //generate order business
         return new JsonResponse();
    }
}

You know App\Controller\OrdersController::placeOrder() and App\Api\Controller::placeOrder are very similar. I just need to copy my code. however copy code is stupid.

do you have some good idea to avod copy code?

1 Like

http://book.cakephp.org/3.0/en/controllers/components.html

Components are packages of logic that are shared between controllers

Take a look at the Friends of Cake CRUD plugin. It is designed for this kind of reusable action logic (And even has fancy API rendering logic built in)


https://crud.readthedocs.io/en/latest/

Take a look at this link: http://book.cakephp.org/3.0/en/development/rest.html This article may be what you are looking for