如何創(chuàng)建支持依賴項(xiàng)注入(di)的 php 函數(shù)庫:創(chuàng)建 composer 包作為函數(shù)庫。實(shí)現(xiàn)函數(shù)庫功能,如在文件中實(shí)現(xiàn)一個(gè)問候函數(shù)。安裝 phpdi 容器并創(chuàng)建容器配置,將函數(shù)庫類作為工廠定義添加到容器中。在代碼中使用函數(shù)庫并注入依賴項(xiàng),如使用容器獲取函數(shù)庫類的實(shí)例。在實(shí)際應(yīng)用中,例如將用戶數(shù)據(jù)保存到數(shù)據(jù)庫,注入數(shù)據(jù)庫連接以提高靈活性。
如何創(chuàng)建 PHP 函數(shù)庫并使其支持依賴項(xiàng)注入
介紹
函數(shù)庫是 PHP 中代碼復(fù)用的強(qiáng)大工具。通過使用依賴項(xiàng)注入(DI),您可以編寫更靈活、可測試的函數(shù)庫。本文將向您介紹如何創(chuàng)建和使用支持 DI 的 PHP 函數(shù)庫。
創(chuàng)建函數(shù)庫
首先,您需要?jiǎng)?chuàng)建一個(gè) Composer 包作為您的函數(shù)庫。使用 composer 包管理器,通過運(yùn)行以下命令創(chuàng)建一個(gè)新包:
composer init
登錄后復(fù)制
填寫包信息,然后運(yùn)行以下命令安裝 Composer 自動加載器:
composer install
登錄后復(fù)制
現(xiàn)在,在您的項(xiàng)目中創(chuàng)建一個(gè)新目錄,用作函數(shù)庫代碼。例如:
php
└── vendor
└── my-library
└── src
└── FunctionLibrary.php
登錄后復(fù)制
實(shí)現(xiàn)函數(shù)庫
在 FunctionLibrary.php 中,實(shí)現(xiàn)函數(shù)庫功能。例如:
namespace MyLibrary;
class FunctionLibrary
{
public function greet(string $name): string
{
return "Hello, $name!";
}
}
登錄后復(fù)制
配置依賴項(xiàng)注入
為了支持 DI,您需要使用一個(gè)容器來解決依賴項(xiàng)。本文將使用 PhpDI 容器。
在您的函數(shù)庫包中安裝 PhpDI:
composer require php-di/phpdi
登錄后復(fù)制
接下來,在 src/config.php 中創(chuàng)建一個(gè)容器配置:
$containerBuilder = new \DI\ContainerBuilder();
$containerBuilder->addDefinitions([
'MyLibrary\FunctionLibrary' => \DI\factory(function () {
return new FunctionLibrary();
})
]);
$container = $containerBuilder->build();
登錄后復(fù)制
使用函數(shù)庫
現(xiàn)在,您可以在代碼中使用您的函數(shù)庫并注入依賴項(xiàng):
use MyLibrary\FunctionLibrary;
use DI\Container;
$container = new Container();
$functionLibrary = $container->get(FunctionLibrary::class);
echo $functionLibrary->greet('John'); // 輸出:Hello, John!
登錄后復(fù)制
實(shí)戰(zhàn)案例
假設(shè)您有一個(gè)將用戶數(shù)據(jù)保存到數(shù)據(jù)庫的函數(shù)庫。您可以在依賴項(xiàng)注入中注入數(shù)據(jù)庫連接,從而使您的函數(shù)庫更加靈活和可測試:
namespace MyLibrary;
class UserRepository
{
private $connection;
public function __construct(\PDO $connection)
{
$this->connection = $connection;
}
public function persist(User $user): void
{
// 保存用戶到數(shù)據(jù)庫
}
}
登錄后復(fù)制
然后,在容器配置中添加以下定義:
$containerBuilder->addDefinitions([
\PDO::class => \DI\factory(function () {
return new \PDO('<a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/15713.html" target="_blank">mysql</a>:host=localhost;dbname=my_database', 'username', 'password');
}),
'MyLibrary\UserRepository' => \DI\factory(function (Container $container) {
return new UserRepository($container->get(\PDO::class));
})
]);
登錄后復(fù)制






