iidestiny / dependency-injection Goto Github PK
View Code? Open in Web Editor NEW✨ Lightweight dependency injection
✨ Lightweight dependency injection
你这不是依赖注入 倒像是静态实例化你的函数...
并没有实现注入效果
How about this way?
<?php
namespace App\Http\Controllers;
class ExampleController extends Controller {
/**
* di helper
*/
protected function make($cls) {
return new class($cls) {
use \Illuminate\Routing\RouteDependencyResolverTrait;
public function __construct($cls)
{
$this->container = app();
$this->ins = app($cls);
}
public function __call($name, $arguments)
{
$this->ins->$name(...$this->resolveClassMethodDependencies($arguments, $this->ins, $name));
}
};
}
/**
* usage
*/
public function store()
{
$this->make(OrderService::class)->placeOrder($user, $goods, $address);
}
}
例如
class Book
{
public function say()
{
echo "book", PHP_EOL;
}
}
class Pen
{
public function say()
{
echo 'pen', PHP_EOL;
}
}
$book = di_register(Book::class);
$pen = di_register(Pen::class);
$book->say();
$pen->say();
将会输出:
pen
pen
查看源码,发现原因出在'Iidestiny\DependencyInjection\App'第21行,
protected static $instance;
因为register
方法每次返回一个新的App
实例,但是instance
却是静态变量
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.