简体   繁体   中英

dependency injection in PHP without interface nor abstract class

I have a class RemoteCall/Client implementing a remote command call. For example, to run by SSH a command on a remote system.

This class uses adapter (for now, I only use a SSH adapter).

RemoteCall/Client.php
RemoteCall/Adapter/AdapterAbstract.php
RemoteCall/Adapter/SSH.php

To implement the SSH protocol, I downloaded an external library (don't ask me now) called Ipworks_SEexec.

Should my class SSH.php use dependency injection between Ipworks_SExec and her ?

public function __construct($driver = null)
{
    $this->_driver = $driver;
}

Or is it better to not implement dependency injection and have something like that :

public function __construct()
{
    $this->_driver = new Ipworks_SEexec();
}

My class SSH.php will works ONLY with the class Ipworks_SEexec. If I decide to use another library, it won't be possible.

There is no "driver", because you are using concrete 3rd party library, so simply require this class:

public function __construct(Ipworks_SExec $ssh_client)
{
...
}

Of course, you can create proxy interface for SSH drivers and implement first adapter based on this Ipworks_SExec class, but that would be overkill if you don't need different adapters right now.

Should my class SSH.php use dependancy injection between Ipworks_SExec and her ?

I'm a bit confused by your question. However, dependency injection is for dynamic loading of dependencies. As you say that your SSH class HAS TO USE Ipworks_SExec then there's probably little point in having dependency injection (just hard code it).

This is unless Ipworks_Exec is really mutable and needs to be set up properly and uniquely for each time you use it in which case you can use dependency injection to make your code more maintainable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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