0
votes

It appear you can write Factories in Laravel.

According to doumentation: https://laravel.com/docs/5.3/database-testing#writing-factories

It appear Factories for the model/database related.

Is it possible to write Factories for non model related?

For example of two classes:

class Car {
  public function drive() { }
} 

Class Bike {
 public function ride() { }
}

Rather than using (new Car)->drive() I would like to use Transport Factory to class the class.

2
If I understand you correctly, you're looking for Mockeries - apokryfos
@apokryfos No I do not want to mock. I want to use factory pattern something like Transport::build('car')->drive(); I wonder if Laravel support such thing. - I'll-Be-Back
Does car have dependencies or would it literally evaluate to (new Car)->drive()? - Rwd
@I'll-Be-Back if you mean the factory pattern then no, you'll have to implement this on your own. Laravel uses the Service Container which works differently but provides a similar (if not better) result. However note that the Factory you're linking to is not what you think it is. That is for database testing. - apokryfos

2 Answers

0
votes

I'd do something like this

class Transport
{
    public static function build($vehicle)
    {
        return new $vehicle;
    }
}

interface Vehicle
{
    public function drive();
}

class Car implements Vehicle
{
    public function drive()
    {
        // the way a car drives
    }
}

class Bike implements Vehicle
{
    public function drive()
    {
        // the way a bike drives
    }
}

class Something
{
    public function someFunc()
    {
        Transport::build('Car')->drive();
    }
}

Here without having separate methods like drive() and ride() for Car and Bike classes, I just added drive() method. Then Bike and Car bind to the Vehicle contract.

So then we just need to pass either a Car or a Bike to Transport::build('Car')->drive();

0
votes

We can create Factory pattern like Transport::build('car')->drive(); as per following.

//Create a class for the dynamic object
class Transport{
    public static function build($vehicle)
    {
        return new $vehicle;
    }
}

//Normal class
class Car {
  public function drive() {

  }
}

//call factory class for dynamic object
Transport::build('Car')->drive();