Php - 在构造函数中创建具有依赖项的类实例

时间:2017-11-23 12:54:48

标签: php laravel

我有一个类,它有一个如下所示的构造函数:

use App\Libraries\Content\ContentInterface;
use EllipseSynergie\ApiResponse\Laravel\Response;

class ImportController extends Controller
{
    private $indexable;

    function __construct(Response $response, ContentInterface $contentInterface) {
        $this->indexable        = \Config::get('middleton.wp.content.indexable_types');
        $this->response         = $response;
        $this->contentInterface = $contentInterface;
    }

    public function all() {
        $include      = array_diff($this->indexable, ['folder']);
        $importResult = $this->import($include);
        $this->deleteOldContent($importResult['publishedPostsIDs']);

        return $importResult['imported'];
    }

如何从另一个类中实例化该类并从中调用方法all()? 我试过这样的事情:

use EllipseSynergie\ApiResponse\Laravel\Response;
use App\Libraries\Content\ContentInterface;

class ContentImport extend Command {

public function handle() {

    (new ImportController(new Response, new ContentInterface))->all();
}

但是,这不起作用,我得到的错误是我应该将参数传递给Response类:

 [Symfony\Component\Debug\Exception\FatalThrowableError]                                                                    
  Type error: Too few arguments to function EllipseSynergie\ApiResponse\AbstractResponse::__construct(), 0 passed in /home/  
  vagrant/Projects/middleton/app/Console/Commands/ContentImport.php on line 43 and exactly 1 expected  

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

我相信这应该有用

use EllipseSynergie\ApiResponse\Laravel\Response;
use App\Libraries\Content\ContentInterface;

class ContentImport extend Command {

    public function handle(ImportController $importController) {

    $importController->all();
}