Zero
Zero

Reputation: 453

Using a variable when loading a class with the "use" statement

I'm working on a Laravel project which is going to be a full API project. I've coded myself a way to do API versioning. I've structured my projects by adding version numbers in the architecture of Laravel.

For example, I'm working on the V0 of my API, I'm going to this architecture with my models : App\Models\V0\MyModel

I was wondering if my any chance, it's possible depending on the current version of the API (which is set in a middleware) to load models depending on that current variable in a use statement ? For example :

use App\Models\V0\User;

Is it possible somehow to stock "V0" into a variable and use it in the "use" to load dynamically the good version of the model ?

Upvotes: 0

Views: 176

Answers (1)

Anton Sukhachev
Anton Sukhachev

Reputation: 139

If you really want to do this, you can create a factory for your model.

<?php

namespace App\Models;

use App\Models\V0\User as UserV0;
use App\Models\V1\User as UserV1;


class UserFactory {
   public static function get(int $version) {
   switch($version){
      case 0:
    return new UserV0();
      case 1:
    return new UserV1();
    }
  }
}

and than use it

<?php

use App\Models\UserFactory;

$version = 0;
$user = UserFactory::get($version);

Upvotes: 1

Related Questions