定制 giuseppe998e/syringe 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

giuseppe998e/syringe

最新稳定版本:1.0.4

Composer 安装命令:

composer require giuseppe998e/syringe

包简介

Dependency injection library for PHP8

README 文档

README

Dependency injection library for PHP8.

Usage

The configuration class:

<?php

use PDO;
use Syringe\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 values
    public function getMariaDBConnection(): PDO {
        $dsn = 'mysql:dbname=mariadb;host=127.0.0.1;port=3307';
        $user = 'root';
        $password = 'password';
        return new PDO($dsn, $user, $password);
    }

    #[Provides(primary: true)]
    public function getMySQLConnection(): PDO {
        $dsn = 'mysql:dbname=mysqldb;host=127.0.0.1;port=3306';
        $user = 'root';
        $password = 'password';
        return new PDO($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:

<?php

use Syringe\Attribute\Inject;

class TestClass {
    #[Inject] // Injects "getMySQLConnection" because it's set as primary
    // #[Inject("getMariaDBConnection")]
    // or #[Inject(qualifier: "getMySQLConnection")]
    private PDO $db;

    public function getUserById(int $id): array {
         $stmt = $db->prepare('SELECT * FROM users WHERE id=?');
         $stmt->execute([$id]);
         return $stmt->fetch();
    }
}

Initialize Syringe:

<?php

use Syringe\Syringe;
use Syringe\Repository\ComponentRepository;

$repo = new ComponentRepository();
$repo->addConfiguration(DbConfiguration::class);
// $repo->addConfiguration(OtherConfiguration::class);
Syringe::initialize($repo);

$testClass = Syringe::new(TestClass::class);
$user = $testClass->getUserById(1);
var_dump($user);

// ...

统计信息

  • 总下载量: 3
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 11
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 11
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2022-10-24

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固