我正在使用symfony 3并尝试访问我在
中声明的类的src /的appbundle /服务/ 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*/ ];
}
}
我在
中声明了这个文件配置/ service.yml
service:
*
*
*
api:
class: AppBundle\Service\ApiEngine
arguments: ["@username", "@repos"]
在控制器中我试图使用一些像这样的ApiEngine方法:
的src /的appbundle /控制器/ 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服务“api”依赖于a 不存在的服务“用户名”。
答案 0 :(得分:1)
我建议你改变你的课程,例如:
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();
在您的控制器中,您需要为use
插入ApiEngine
,在此用例中您不需要依赖注入,因此请在services.yml
删除参数中