Javascript Slim框架:Currying与依赖注入
在一些框架(如Angular)中,您可以像这样将服务和控制器相互注入Javascript Slim框架:Currying与依赖注入,javascript,php,angularjs,dependency-injection,slim,Javascript,Php,Angularjs,Dependency Injection,Slim,在一些框架(如Angular)中,您可以像这样将服务和控制器相互注入 App.controller('exampleController', function($scope, ajaxService){ ajaxService.getData().then(function(data) { //do something with the data }); }); $app->get('/example', function() use ($app,
App.controller('exampleController', function($scope, ajaxService){
ajaxService.getData().then(function(data) {
//do something with the data
});
});
$app->get('/example', function() use ($app, $db) {
$data = $db->getData();
//do something with the data
}
这被称为对文档的依赖项注入
你也可以在苗条的框架里做这样的事情,像这样
App.controller('exampleController', function($scope, ajaxService){
ajaxService.getData().then(function(data) {
//do something with the data
});
});
$app->get('/example', function() use ($app, $db) {
$data = $db->getData();
//do something with the data
}
这被称为“咖喱”
据我所知,这些是完全一样的东西吗?为什么叫不同的名字?这里有几篇有趣的文章: 无论是编程语言还是框架,我们都可以说“依赖注入”(DI)类似于 OOP类定义中的委托(参见示例)和Currying是完全不同的,比如函数参数简化 DI允许您保持类的简单和解耦。如果您熟悉Laravel,ServiceProvider就是一个很好的例子。简而言之,您的类有一个属性,该属性将被设置为另一个类的实例(通常实现一个接口),以便您可以委托一些功能。典型的例子是:
interface LogInterface {
public function write();
}
class LogToFile implements LogInterface {
public function write()
{
//Do something
}
}
class LogToFileDB implements LogInterface {
public function write()
{
//Do something
}
}
class MyDIClass {
private $log;
public function __construct(LogInterface $log){
$this->log = $log;
}
public function writeLog(){
$this->log->write();
}
}
//You can do
$myobj = new MyDIClass(new LogToFile);
//or you can do
//$myobj = new MyDIClass(new LogToDB);
//this will work, no worries about "write()" you are delegating through DI
$myobj->writeLog();
我刚刚在上面写了这段代码(可能没有功能)来说明DI。使用该接口可以确保方法“write()”将在任何实现LogiInterface的类中实现。然后,在实例化对象时,类强制获取LogiInterface对象。忘记“write()”是如何工作的吧,这不关你的事
至于咖喱,技巧是不同的,你只需简化函数中的参数。当使用Slim框架时,这些家伙说“你可以通过使用$app来实现你的路线”。我经常使用Slim,我的理解是,好吧,比传递几个变量到路由闭包更重要的是,只需充实$app变量并传递1个var:$app
$app = new \Slim\Slim();
//Rather than
//$app->get('/foo', function () use ($app, $log, $store, ...) {
$app->get('/foo', function () use ($app) {
$app->render('foo.php'); // <-- SUCCESS
$app->log->write();
$app->db->store();
});
$app=new\Slim\Slim();
//而不是
//$app->get('/foo',函数()使用($app,$log,$store,…){
$app->get('/foo',函数()使用($app){
$app->render('foo.php');//log->write();
$app->db->store();
});