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

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

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)