Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Dependency injection library for PHP8

License

NotificationsYou must be signed in to change notification settings

giuseppe998e/syringe

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

47 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Dependency injection library for PHP8.

Usage

The configuration class:

<?phpusePDO;useSyringe\Attribute\{Provides,Qualifier};class DbConfiguration {// bool "primary" - Sets the Provides as primary if more than one of the same type is available.// ?string "name" - Custom name (or qualifier) for the Provides. (Set "null" to use the method name)// bool "singleton" - Denotes that the Provides is a singleton    #[Provides(primary:false, name:null, singleton:true)]// Default valuespublicfunctiongetMariaDBConnection():PDO {$dsn ='mysql:dbname=mariadb;host=127.0.0.1;port=3307';$user ='root';$password ='password';returnnewPDO($dsn,$user,$password);    }    #[Provides(primary:true)]publicfunctiongetMySQLConnection():PDO {$dsn ='mysql:dbname=mysqldb;host=127.0.0.1;port=3306';$user ='root';$password ='password';returnnewPDO($dsn,$user,$password);    }/*    public function getCarsRepository(        // Without "Qualifier" the parameter will be bound to        // "getMySQLConnection" (because it's primary for the PDO class)        #[Qualifier("getMariaDBConnection")] PDO $db    ): CarsRepository {        return new CarsRepository($db);    }*/// ...}

The component class:

<?phpuseSyringe\Attribute\Inject;class TestClass {    #[Inject]// Injects "getMySQLConnection" because it's set as primary// #[Inject("getMariaDBConnection")]// or #[Inject(qualifier: "getMySQLConnection")]privatePDO$db;publicfunctiongetUserById(int$id):array {$stmt =$db->prepare('SELECT * FROM users WHERE id=?');$stmt->execute([$id]);return$stmt->fetch();    }}

Initialize Syringe:

<?phpuseSyringe\Syringe;useSyringe\Repository\ComponentRepository;$repo =newComponentRepository();$repo->addConfiguration(DbConfiguration::class);// $repo->addConfiguration(OtherConfiguration::class);Syringe::initialize($repo);$testClass = Syringe::new(TestClass::class);$user =$testClass->getUserById(1);var_dump($user);// ...

[8]ページ先頭

©2009-2025 Movatter.jp