Home > other >  Improved class structure in php
Improved class structure in php

Time:03-01

I have a number of classes in php that for each function in that class I have to put some code at the beginning, for example:

class OrderController
{

  public function list()
  {
    $user_id = $_SESSION["user_id"];
    $check_access = CheckAccess($user_id,'order','list_func');
    if(!$check_access) die(403);
    $access_level = $check_access['level'];
    ....
  {

  public function get()
  {
    $user_id = $_SESSION["user_id"];
    $check_access = CheckAccess($user_id,'order','get_func');
    if(!$check_access) die(403);
    $access_level = $check_access['level'];
    ....
  {
 } 

I have to repeat a piece of code below to check the access of each person in each function of the class:

    $user_id = $_SESSION["user_id"];
    $check_access = CheckAccess($user_id,'order','get_func');
    if(!$check_access) die(403);

Is there a way for me to clean up my code without having to repeat it every time?

CodePudding user response:

What you can do is extract the common parts of the logic to a private method and call as needed. The CLEANER solution would be to have a different class, a dedicated class, check the access of the customers and not to do it from the controller. From a clean code perspective, you need to think about the single responsibility principle .

You can also create a BaseController class which has this logic inside in a protected method, and all of your other controllers will extend from it.

class OrderController
{
    public function list(Request $request)
    {
        $check_access = $this->hasCustomerAccessOrDie($request, 'list_func');
        $access_level = $check_access['level'];
    }

    public function get(Request $request)
    {
        $check_access = $this->hasCustomerAccessOrDie($request, 'get_func');
        $access_level = $check_access['level'];
    }

    private function hasCustomerAccessOrDie(Request $request, string $permission): bool # I guess it is a boolean
    {
        $user_id = (int)$request->user_id;
        $check_access = CheckAccess($user_id, 'order', $permission);
        if (!$check_access) die(403);
        return $check_access;
    }
}

CodePudding user response:

You can use trait to use a method inside different classes. As an example:

trait Authorization {
    private function authorize(int $user_id, string $permission)
    {
        if (!CheckAccess($user_id, 'order', $permission)) {
            die(403);
        }
    }
}

class OrderController
{
    use Authorization;

    public function list(Request $request)
    {
        $this->authorize($request->user_id, 'list_func');

        $access_level = $check_access['level'];
    }

    public function get(Request $request)
    {
        $this->authorize($request->user_id, 'get_func');

        $access_level = $check_access['level'];
    }
}

Link: https://www.w3schools.com/php/php_oop_traits.asp

  • Related