duanbipu1720
2017-06-06 11:58
浏览 74
已采纳

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

I am using symfony 3 and trying to get access to the class I declared in

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*/ ];
    }
}

I declared this file in

config/service.yml

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

In controller I am trying to use some of the ApiEngine methods like this:

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);
    } }

But it gives me this error:

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doutuo4285 2017-06-06 12:01
    已采纳

    I advise you to change your class into this for example:

    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);
    }
    

    After inside your controller you can do this:

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

    Into your controller you need to insert a use for ApiEngine, in this use case you don't need dependency injection so inside your services.yml remove arguments please

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题