Symfony - 从控制器中的另一个文件访问方法

Symfony - get access to the method from another file in controller

我正在使用 symfony 3 并试图访问我在

中声明的 class

src/AppBundle/Service/ApiEngine.php

namespace AppBundle\Service;


use DateTime;

class ApiEngine {

    private $api_handler;

    public function __construct($username, bool $repos) {
        $client = new \GuzzleHttp\Client();
        $request = 'https://api.github.com/users/' . $username;
        $request .= ($repos) ?  '/repos' : "";
        $res = $client->request('GET', $request);

        $this->api_handler = json_decode($res->getBody()->getContents(), true);
    }

    public function getProfileData() {
        return [ /*some data*/ ];
    }
}

我在

中声明了这个文件

config/service.yml

service:
  *
  *
  *
  api:
      class: AppBundle\Service\ApiEngine
      arguments: ["@username", "@repos"]

在控制器中,我正在尝试使用这样的一些 ApiEngine 方法:

src/AppBundle/Controller/GitApiController.php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class GitApiController extends Controller {

    /**
     * @Route("/{username}", name ="gitapi", defaults={"username": "symfony"})
     */
    public function gitApiAction($username) {
        $api = $this->get('api')->__construct($username, false)->getProfileData();

        return $this->render('gitapi/index.html.twig', $api);
    } }

但是它给我这个错误:

(1/1) ServiceNotFoundException The service "api" has a dependency on a non-existent service "username".

我建议你把你的 class 改成这样,例如:

private function __construct($username, bool $repos) {
        $client = new \GuzzleHttp\Client();
        $request = 'https://api.github.com/users/' . $username;
        $request .= ($repos) ?  '/repos' : "";
        $res = $client->request('GET', $request);

        $this->api_handler = json_decode($res->getBody()->getContents(), true);
    }

public static function createApiEngine($username, bool $repos) 
{
    return new self($username, $bool);
}

进入控制器后,您可以这样做:

$api = ApiEngine::createApiEngine($username, false);
$api->getProfileData();

您需要为 ApiEngine 插入一个 use 到您的控制器中,在这个用例中您不需要依赖注入,所以请在您的 services.yml 中删除参数