vendredi 2 septembre 2016

Trying to reuse code in API and Non Api Controller

I have two controllers. One method is common in both controller. Store

Let me show both controllers.

Api Controller

class RoleApiController extends Controller
{
    private $Role;

    public function __construct(IRole $_role) {
        $this->Role = $_role;
    }

    private function InitializeInputs(RoleRequest $request) {
        if($request["ParentRoleID"] == -1) {
            $request["ParentRoleID"] = null;
        }
    }

    public function store(RoleRequest $request)
    {
        $this->InitializeInputs($request);

        $obj = new RoleOM();
        $obj->Role          = $request["Role"];
        $obj->ParentRoleID  = $request["ParentRoleID"];
        $obj->Active      = !is_bool($request["Active"]) ? false : $request["Active"];

        $result = $this->Role->Create($obj);

        return  \Response::json([
            'Status'   => $result["Success"],
            'Message'  => $result["ErrorMessage"]
        ]);
    }
}

Below is the controller for blade

class RoleController extends \App\Http\Controllers\BaseController
{
    private $Role;

    public function __construct(IRole $_role) {
        $this->Role = $_role;
        parent::__construct();
    }

    private function InitializeInputs(RoleRequest $request) {
        if($request["ParentRoleID"] == -1) {
            $request["ParentRoleID"] = null;
        }
    }

    public function store(RoleRequest $request)
    {
        $this->InitializeInputs($request);

        $obj = new RoleOM();
        $obj->Role          = $request["Role"];
        $obj->ParentRoleID  = $request["ParentRoleID"];
        $obj->Active      = !is_bool($request["Active"]) ? false : $request["Active"];

        $result = $this->Role->Create($obj);

        return  \Response::json([
            'Status'   => $result["Success"],
            'Message'  => $result["ErrorMessage"]
        ]);
    }
}

Question

If I use Trait: I don't need to write the action methods. So Controller will have no such method called Trait.

If I use class and define a method there, in that case, I will instantiate the class method in both controller's action method.

Please suggest.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire