Fine structure: Currying vs Dependency Injection

In some frameworks like Angular, you can inject services and controllers into others like this

App.controller('exampleController', function($scope, ajaxService){ ajaxService.getData().then(function(data) { //do something with the data }); }); 

This is called Injection Dependency according to Angular docs

You can also do something similar in Slim Framwork, for example

 $app->get('/example', function() use ($app, $db) { $data = $db->getData(); //do something with the data } 

This is called Currying according to Slim docs .

As far as I can see, is it the same? Why are they called by different names?

+6
source share
1 answer

A couple of interesting readings here: What is currying What is dependency injection

Regardless of the programming language or structure, we can say that "Injection of Dependency" (DI) is something like delegation in the definition of an OOP class (see example), and Currying is something completely different, say simplification of function parameters.

DI allows you to maintain simple and maladaptive classes. If you are familiar with Laravel, ServiceProvider is a good example. In a nutshell, your class has a property that will be set to an instance of another class (usually implementing an interface) so that you can delegate some functions. A typical example:

 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(); 

I just wrote this code above (maybe not working) to illustrate the DI. Using the interface, you guarantee that the "write ()" method will be implemented in any class that implements LogInterface. Then your class forces you to get a LogInterface object when creating objects. Forget how write () works; it's not your business.

Regarding Currying, the technique is different; you simply simplify the parameters in the function. When using the Slim Framework, the guys say, "You can curry your routes using the $ app." I used Slim a lot, and I understand that this is normal, rathaer, than passing multiple variables to your route locks, just enrich the $ app variable and pass 1 one-time 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(); }); 
+2
source

Source: https://habr.com/ru/post/979580/


All Articles