Reputation: 10828
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.
Upvotes: 0
Views: 383
Reputation: 1609
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();
Upvotes: 0
Reputation: 3704
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();
Upvotes: 0