skip to Main Content

I work on legacy code and this problem founded, I work on OrderService and in createOrder() method is static method and i want to check on the store is open or not?

I want to make non-static method openingHours() to check in times.

Do i can use ReflactionClass in this solution?

when use openingHours() in createOrder() erro hapen:

Cannot use ‘$this’ in non-object context.intelephense(1030)

$this can not be used in static methods.php

createOrder() method:

 public static function createOrder(array $data {
// some logic 
 
     $is_opening = $this->openingHours($store);

     if ($is_opening  != true) {
     $msg              = trans('stores.not_available');
     $data['fail_msg'] = $msg;
      return $data;
     }

}

openingHours()

 public function openingHours($store){
      
 returne 'hello';
    }

3

Answers


  1. Either createOrder can not be static or openingHours has to be static too.
    Except if you have or create an instance in createOrder on which you can call the non static method openingHours like $store->openingHours().

    Login or Signup to reply.
  2. Consider to transform createOrder() in a non-static function.

    If this is not feasible, the only way is to create an instance of the class in the static function:

    $is_opening = (new static)->openingHours($store);
    

    or, if you need the dependency injection:

    $is_opening = app (__CLASS__)->openingHours($store);
    
    Login or Signup to reply.
  3. Can you tell me what is the meaning of $store variable? I guess it maybe holds the Store Model object, so I suggest to put openingHours() method in the Store Model Class.

    <?php
     
    namespace AppModels;
     
    use IlluminateDatabaseEloquentModel;
     
    class Store extends Model
    {
        // ...
        public function isInOpeningHours(): bool // you can pass current timestamp or whatever you need to check this.
        {
            // ...
        }
    }
    

    Better than that I suggest to create a getter in your Store Model Class to get the opening hours in a form that is good to make a validation on it.

    <?php
     
    namespace AppModels;
     
    use IlluminateDatabaseEloquentModel;
     
    class Store extends Model
    {
        // ...
        public function getOpeningHours(): array
        {
            // ...
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search