简体   繁体   English

Symfony-通过服务容器传递ZipArchive(PHP核心类)类

[英]Symfony - Pass ZipArchive (PHP core class) class through service container

I need to pass ZipArchive class as a dependency for one of my class. 我需要通过ZipArchive类作为我的一个类的依赖项。 I hope it is possible to do but no idea how to define in services.yml file. 我希望可以这样做,但不知道如何在services.yml文件中进行定义。

Any idea please. 任何想法,请。

You can pass your ZipArchive class as service's argument 您可以将ZipArchive类作为服务的参数传递

First, you need to create service for ZipArchive 首先,您需要为ZipArchive创建服务

services:
    lib.ziparchive:
        class: Lib\ZipArchive   #your ZipArchive Class Namespace


Then you can pass lib.ziparchive to your class service 然后,您可以将lib.ziparchive传递给类服务

    app.my_service:
        class: AppBundler\Services\MyService
        arguments: ['lib.ziparchive']


In your MyService Class, you need to create constructor. 在MyService类中,您需要创建构造函数。

namespace AppBundle\Services;

use Lib\ZipArchive

class MyService
{
    protected $ziparchive;

    public function __construct(ZipArchive $ziparchive)
    {
        $this->ziparchive = $ziparchive;
    }

}

Check more detail for service container 检查服务容器的更多详细信息

Hope it help. 希望对您有所帮助。

I'd instantiate the core php object in the service construct and provide a setter to override this object (ie for testing later on): 我将实例化服务构造中的核心php对象,并提供一个setter来覆盖此对象(即稍后进行测试):

services.yml: services.yml:

app.my_service:
    class: AppBundler\Services\MyService

AppBundle\\Services\\MyService: 的appbundle \\ SERVICES \\为MyService:

namespace AppBundle\Services;

class MyService
{
    protected $ziparchive;

    public function __construct()
    {
        $this->ziparchive = new ZipArchive();
    }

    public function setZipArchive(\ZipArchive $zipArchive)
    {
        $this->zipArchive = $zipArchive;

        return $this;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM