Baa框架中的依赖注入(DI)是个什么鬼?
我最早接触的Go WEB框架是 beego,很强大的一个框架,也是很多人的首选,就是因为太(bu)强(gou)大(ling)了(huo),后来尝试了 Macaron(martini)。Macaron的设计是众多框架的主流思想,路由、中间件、HTTP上下文,然后自己实现了一些常用的中间件(PS. 有一些中间件代码来自beego)。Macaron的思想中,可以通过m.Map()注入任意类型,然后在Context中通过反射获取这个类型,初试很爽,并为他的设计称赞。
在用PHP的时候有个框架 Phalcon他的设计中核心是 Dependency Injection/Service Location,看起来很复杂,简单来说就是把类似log,db,cache,metadata等服务注册到DI中,使用的时候从DI取出来。Phalcon的使用姿势中就是先初始化一个APP,然后各种注册DI,然后RUN,伪代码如下:
<?php$di = new \Phalcon\DI\FactoryDefault();$di->set('router', new MyRouter());$di->set('logger', function () { return new LoggerFile('../apps/logs/error.log');});$di->set('db', function () { return new PdoMysql( array( "host" => "localhost", "username" => "root", "password" => "secret", "dbname" => "blog" ) );});$di->set('db2', ...);$di->set('mongo', new \MongoClient());// Create an application$application = new \Phalcon\Mvc\Application($di);// Handle the requestecho $application->handle()->getContent();
上面的初始化,就是各种set,当然他支持set的类型比较丰富,还支持lazyload等,使用的方式也比较简单:
<?php$di = new \Phalcon\DI\FactoryDefault();$db = $di->get('db');$mongo = $di->get('mongo');$mongo->selectCollection('xxx');
总结下来,就是 set/get,set就是设置一个服务(注入),get就是取出这个服务来使用,当然php不像Go是静态语言,他不需要做类型断言。
介绍完背景,其实也问题也基本明确了,在使用macaron的过程中,过分依赖反射,导致同一种类型只能注册一个,比如我要两个db,两个logger类型一致但做不同的服务用途,就比较难了。其实我最痛苦的是logger,macaron框架中使用了原声的log包,我无论怎么写都做不到日志统一,框架中输出的日志不依赖注入,就是原生的log。结合我对Phalcon的经验,就萌生了把Phalon DI的思想移植过来的念头,再结合其他想法,就去做了Baa。DI是Baa中目前写得最简单的东西,但是却是最直接导致去造轮子的。
再来看Baa的DI思想特别简单,就是一个set一个get,使用姿势和Phalcon也一样,只不过目前没有提供那么多姿势的支持,比如懒加载(匿名函数)在调用时初始化,静态类就是set一个字符串使用的时候去new。虽然简单,但思想并无差别。我们可以做个示例:
package mainimport ( "github.com/go-baa/cache" _ "github.com/go-baa/cache/redis" "github.com/go-baa/render" "gopkg.in/baa.v1")func main() { // new app app := baa.New() // register logger app.SetDI("logger", log.Logger) // register render b.SetDI("render", render.New(render.Options{ Baa: app, Root: "templates/", Extensions: []string{".html", ".tmpl"}, FuncMap: template.Funcs(b), })) // register cache app.SetDI("cache", cache.New(cache.Options{ Name: "cache", Prefix: "MyApp", Adapter: "memory", Config: map[string]string{}, })) app.SetDI("cache2", cache.New(cache.Options{ Name: "cache2", Prefix: "MyApp2", Adapter: "redis", Config: map[string]string{}, })) // router app.Get("/", func(c *baa.Context) { ca := c.DI("cache").(cache.Cacher) ca.Set("test", "baa", 10) v := ca.Get("test").(string) c.String(200, v) }) // run app app.Run(":1323")}
在app的初始化中通过set我们注入logger,render,cacher,甚至db的初始化等,在需要的地方比如Context中,context.DI()来获取,或者在其他地方可以 baa.Default().GetDI()来获取使用。再看我上面吐槽的log,在这里你只要 app.SetDI("logger", xxx)即可以替换掉框架内置的logger,render也一样,只要注册一个实现了baa.Renderer接口的render就可以自定义模板引擎。
依赖注入(DI)不是什么玩意,虽然只有几行代码,但他是一种设计思想,一种理念,一种解决问题的姿势。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
