简体   繁体   中英

How to include php class that extends an interface

I'm developing a socket listener that has to process data with CommandService class.

CommandService.php

<?php
namespace Application\Service;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;

class CommandService implements ServiceLocatorAwareInterface
{
    use ServiceLocatorAwareTrait;

} 

custom.php

<?php
include('../module/Application/src/Application/Service/CommandService.php');
?>

And when I run on console

php custom.php

I get error: Fatal error: Interface 'Zend\\ServiceManager\\ServiceLocatorAwareInterface' not found in C:\\wamp\\www\\nutirent\\module\\Application\\src\\Application\\Service\\CommandService.php on line 7

So I't would be great if someone can give me some advice how can I get this running without making custom.php as class.

If you are not using any automated loading system (ie composer's autoloader) then its your responsibility to load all the dependencies.

So in this case just loading the CommandService is not enough and you also need to load (include) Zend\\ServiceManager\\ServiceLocatorAwareInterface as well as all the other dependencies :)

So I would strongly suggest to consider using an autoloader ;)

Ali's answer is completely right, i just wanna say something about ServiceLocatorAwareInterface :

Some time ago, I was a big fan of ServiceLocatorAwareInterface in my Services. Now I'm not so sure about it. You have to consider this :

Have the ServiceLocator in your Services make them trashy.

Because the service Locator is what it is, you can't say anymore what's your class depends on, because potentially everything. You should use Dependancy injection instead, and load anything your Service needs in it with Factories, Factories are the only place you can use ServiceLocator, this is the place it belongs.

Ocramius said that better than i'm trying to say right now, so i link here his work about it :

Ocramius Zf2 best Practises

This inspired me. I hope you too.

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