skollro / factory
PHP 的高级工厂。
v1.0.1
2018-04-05 12:16 UTC
Requires (Dev)
- phpunit/phpunit: ^7.0
This package is auto-updated.
Last update: 2024-09-29 05:01:55 UTC
README
此包提供了一种声明式的高级语法来实现工厂模式。
use function Skollro\Factory\make; class VehicleFactory { public static function make($type) { return make($type) ->resolve('car', Car::class) ->resolve('bike', Bike::class) ->resolve([ 'truck' => Truck::class, 'bus' => Bus::class, ]) ->otherwiseThrow(InvalidArgumentException::class); } } $car = VehicleFactory::make('car'); // returns instance of Car $truck = VehicleFactory::make('truck'); // returns instance of Truck $motorcycle = VehicleFactory::make('motorcycle') // throws InvalidArgumentException
安装
您可以通过 composer 安装此包。
composer require skollro/factory
使用方法
每个 make
由一个或多个 resolve
和一个 otherwise
组成,为每个路径提供值。
make($type): 工厂
此包提供了一个 make
辅助函数。
use Skollro\Factory\Factory; use function Skollro\Factory\make; $factory = make($type); $factory = Factory::make($type);
resolve($type, $resolvable = null): 工厂
$type
是实例的标识符。$type
还接受一个关联数组,将标识符映射到类名。$resolvable
可以是某个类名或返回实例的可调用对象。
$object = make('bike') ->resolve('car', Car::class) ->resolve('bike', function () { return new Bike; }) ->resolve('bike', MountainBike::class) // this is not the first match and thus not the result ->resolve([ 'truck' => Truck::class, 'bus' => Bus::class, ]) ->otherwiseThrow(InvalidArgumentException::class); // $object is an instance of Bike
otherwise($resolvable)
$resolvable
是某个类名或返回实例的可调用对象。如果没有匹配到 resolve
,则提供默认实例。
$object = make('motorcycle') ->resolve([ 'car' => Car::class, 'bike' => Bike::class, ]) ->otherwise(Vehicle::class); // $object is an instance of Vehicle $object = make('motorcycle') ->resolve([ 'car' => Car::class, 'bike' => Bike::class, ]) ->otherwise(function () { return new Vehicle; }); // $object is an instance of Vehicle
otherwiseThrow($resolvable)
$resolvable
是某个异常类名或返回异常的可调用对象。如果没有匹配到 resolve
,则抛出异常。
$object = make('motorcycle') ->resolve([ 'car' => Car::class, 'bike' => Bike::class, ]) ->otherwiseThrow(InvalidArgumentException::class); // throws an InvalidArgumentException
Factory::resolveUsing($resolver)
resolveUsing
是 Factory
的静态方法。您可以使用自定义解析器从类名解析实例,例如依赖注入容器。如果没有设置解析器,则使用 new
创建所需类的实例。
与 Laravel 的集成
// in your AppServiceProvider Factory::resolveUsing(function ($className) { return app($className); }); // in your code $object = make('car') ->resolve('car', Car::class) ->otherwiseThrow(InvalidArgumentException::class); // $object is an instance of Car, resolved by Laravel container
许可证
MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件。