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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多