Symfony 2.5 "You have requested a non-existent service "siteTest.b" - php

When run workspace/app_dev.php, no problem. But when I try to run workspace/app.php I get:
"You have requested a non-existent service "siteTest.b"
I dont have the first clue what am I doing wrong.
app/config/config.yml :
imports:
- { resource: parameters.yml }
- { resource: security.yml }
framework:
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
templating:
engines: ['twig']
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
handler_id: ~
fragments: ~
http_method_override: true
src/Site/TestBundle/Resources/config/services.yml:
parameters:
siteTest.aa: Site\TestBundle\Controller\a
services:
siteTest.b:
class: %siteTest.aa%
src/Site/TestBundle/DependencyInjection/SiteTestExtension.php :
namespace Site\TestBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
class SiteTestExtension extends Extension
{
/**
* {#inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
src/Site/TestBundle/Controller/a.php :
namespace Site\TestBundle\Controller;
class a {
public function printTest() {
var_dump('Test');
exit;
}
}
src/Site/TestBundle/Controller/DefaultController.php:
namespace Site\TestBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
public function indexAction()
{
$aaa = $this->get('siteTest.b');
exit();
}
}

you might also need to add the code below inside
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: '#TestBundle/Resources/config/services.yml' }
alternatively you can use the cookbook configurations http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class

run command php app/console cache:clear --env=prod to clear your prod cache

Related

Autowiring problem with parameter injection in Symfony 5

I'm having troubles trying to retrieve a manager from a controller in Symfony 5.
I've got this MailerManager in src/Manager/MailerManager.php:
<?php
namespace App\Manager;
use App\Client\MailjetClient;
class MailerManager {
private $mailjetClient;
function __construct(MailjetClient $mailjetClient) {
$this->setMailjetClient($mailjetClient);
}
function send($data) {
}
function getMailjetClient() {
return $this->mailjetClient;
}
private function setMailjetClient($mailjetClient) {
$this->mailjetClient = $mailjetClient;
}
}
This manager needs to inject src/Client/MailjetClient.php in order to work, that has got this code:
<?php
namespace App\Client;
use \Mailjet\Resources;
class MailjetClient {
private $client;
function __construct(string $apikey, string $apisecret) {
$this->setClient($apikey, $apisecret);
}
function getClient() {
return $this->client;
}
function setClient($apikey, $apisecret) {
$this->client = new \Mailjet\Client($apikey, $apisecret);
}
}
This is just a wrapper for the mailjet sdk installed via composer, that needs to be feeded with different $apikey and $apisecret depending on the environment, for what I'm using parameters through services.yaml file, where I also have got autowiring enabled and service definitions for both MailjetClient and MailerManager:
parameters:
rabbitmq:
host: '%env(RABBITMQ_HOST)%'
port: '%env(RABBITMQ_PORT)%'
user: '%env(RABBITMQ_USER)%'
pwd: '%env(RABBITMQ_PWD)%'
mailjet:
apikey: '%env(MAILJET_APIKEY)%'
apisecret: '%env(MAILJET_APISECRET)%'
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
App\Client\MailjetClient\:
resource: '../src/Client/MailjetClient.php'
arguments:
$apikey: '%mailjet.host%'
$apisecret: '%mailjet.port%'
App\Manager\MailerManager\:
resource: '../src/Manager/MailerManager.php'
arguments:
$mailjetClient: '#client.mailjet'
The problem I'm having is that I'm getting this error: Cannot autowire service "App\Client\MailjetClient": argument "$apikey" of method "__construct()" is type-hinted "string", you should configure its value explicitly. when I try to inject the MailManager in the src/Controller/MailerController.php controller:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use App\Manager\MailerManager;
class MailerController extends AbstractController
{
/**
* #Route("/compose", name="compose")
*/
public function compose(MailerManager $mailerManager)
{
dump($mailerManager);die();
}
}
}
What could posibbly be wrong? I'm coming from Symfony 2, and this parameter injection was something standard that used to work like a charm, now I'm totally confused about how to mix the autowiring with the service manual definition.
I had a total disaster on the services.yml side, thanks to u_mulder and Tejas Gosai hints I could finally put this to work. I had a few type errors on the parameters I was injecting, the MailManager.php specific declaration was not needed, and my client namespaces should not end with \ ad u_mulder suggested.
Finally, with this services.yml it works:
parameters:
rabbitmq.host: '%env(RABBITMQ_HOST)%'
rabbitmq.port: '%env(RABBITMQ_PORT)%'
rabbitmq.user: '%env(RABBITMQ_USER)%'
rabbitmq.pwd: '%env(RABBITMQ_PWD)%'
mailjet.apikey: '%env(MAILJET_APIKEY)%'
mailjet.apisecret: '%env(MAILJET_APISECRET)%'
services:
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
App\Client\MailjetClient:
arguments:
$apikey: '%mailjet.apikey%'
$apisecret: '%mailjet.apisecret%'
App\Client\RabbitClient:
arguments: ['%rabbitmq.host%','%rabbitmq.port%','%rabbitmq.user%','%rabbitmq.pwd%']

Symfony event subscriber not working even service is defined

I have an event subscriber:
namespace App\EventListener;
use App\Entity\Token;
use App\Model\EncryptUtils;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\Common\EventSubscriber;
class DatabaseSubscriber implements EventSubscriber
{
public function getSubscribedEvents()
{
return array(
'prePersist'
);
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getObject();
if ($entity instanceof Token) {
$enityt->setCreatedAt(new \DateTime());
}
}
}
And I've declared the service in services.yaml:
parameters:
locale: 'en'
services:
App\EventListener\DatabaseSubscriber:
tags:
- { name: doctrine.event_subscriber, connection: default }
_defaults:
autowire: true
autoconfigure: true
public: false
bind:
$appSecret: '%kernel.secret%'
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
But there's no way to get it working. I've also tried with an event listener but nothing happens
You should declare your service after all the default configuration because if not, the default configuration is overriding yours.
So your services.yaml file should be:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
bind:
$appSecret: '%kernel.secret%'
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
App\EventListener\DatabaseSubscriber:
tags:
- { name: doctrine.event_subscriber, connection: default }

Symfony 4 -- error when I try to create a Session Proxy

I follow the instructions in https://symfony.com/doc/master/session/proxy_examples.html,
I update my framework.yaml
framework:
secret: '%env(APP_SECRET)%'
#default_locale: en
#csrf_protection: ~
#http_method_override: true
# uncomment this entire section to enable sessions
session:
# With this config, PHP's native session handling is used
handler_id: App\Session\CookieEncryptedSession
#esi: ~
#fragments: ~
php_errors:
log: true
I also create my ownclass:
<?php
namespace App\Session;
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
class CookieEncryptedSession extends SessionHandlerProxy
{
private $key;
public function __construct(\SessionHandlerInterface $handler, Key $key)
{
$this->key = $key;
parent::__construct($handler);
}
public function read($id)
{
$data = parent::read($id);
return Crypto::decrypt($data, $this->key);
}
public function write($id, $data)
{
$data = Crypto::encrypt($data, $this->key);
return parent::write($id, $data);
}
}
When I try to run the server with the console I get this error:
In CheckCircularReferencesPass.php line 67:
Circular reference detected for service "App\Session\CookieEncryptedSession
", path: "App\Session\CookieEncryptedSession -> App\Session\CookieEncrypted
Session".
Any idea where is the mistake?
Thanks
Oskar
The autowiring is trying to inject the service to itself as the service implements the interface required on the constructor. CookieEncryptedSession implements SessionHandlerInterface via:
class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface
Setup in your services the service: CookieEncryptedSession manually so you can select the SessionHandlerInterface service you want.
NativeSessionHandler
NativeFileSessionHandler
DbalSessionHandler
Etc

Routing is not work in Symfony 3.2

I use example from docs.
This is
routing.yml:
app:
resource: '#AppBundle/Controller/'
type: annotation
blog_list:
path: /blog/{page}
defaults: { _controller: AppBundle:Blog:list , page: 1}
requirements:
page: '\d+'
And this controller:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class BlogController extends Controller
{
/**
* #Route("/blog/{page}", name="blog_list", requirements={"page": "\d+"})
*/
public function listAction($page = 1)
{
$number = mt_rand(0, 100);
return $this->render('lucky/number.html.twig',['number'=>$number]);
}
}
I see errors:
The routing file "/var/www/pars/app/config/routing.yml" contains unsupported keys for "app": "blog_list". Expected one of: "resource", "type", "prefix", "path", "host", "schemes", "methods", "defaults", "requirements", "options", "condition" in /var/www/pars/app/config/routing.yml (which is being imported from "/var/www/pars/app/config/routing_dev.yml").
WHY?
Seems only an indentation problem: the new route should be at the low level:
app:
resource: '#AppBundle/Controller/'
type: annotation
blog_list:
path: /blog/{page}
defaults: { _controller: AppBundle:Blog:list , page: 1}
requirements:
page: '\d+'
Hope this help

Error configuring a particular provider for my web application

[Symfony\Component\Debug\Exception\ContextErrorException]
Catchable Fatal Error: Argument 2 passed to Symfony\Component\Security\Core\Authentication\Provider\SimpleAuthenticationProvider::__construct() must implement interface Symfony\Component\Security\Core\User\UserProviderInterface, instance of Delivve\WebBundle\Service\WebKeyUsersService given, called in /home/delivve-webservice/app/cache/de_/ap_DevDebugProjectContainer.php on line 4611 and defined
What happens is that I have an api that works, but now I need to make the web service log face or google account, but this error of the above, follow this tutorial to make
http://nyrodev.info/fr/posts/286/Connexions-OAuth-Multiple-avec-Symfony-2-3
And apena in OAuthMembersService.php file includes the useSymfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface; because symfony complained of is not having such imports.
I'm really doubt
I implemented the following classes:
<?php
namespace Delivve\WebBundle\Security;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUser as BaseOAuthUser;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
class WebKeyUserProvider extends BaseOAuthUser {
protected $data;
public function __construct(UserResponseInterface $response) {
parent::__construct($response->getUsername());
$this->data = array(
'provider'=>$response->getResourceOwner()->getName(),
'providerId'=>$response->getUsername()
);
$vars = array(
'nickname',
'realname',
'email',
'profilePicture',
'accessToken',
'refreshToken',
'tokenSecret',
'expiresIn',
);
foreach($vars as $v) {
$fct = 'get'.ucfirst($v);
$this->data[$v] = $response->$fct();
}
}
public function getData() {
return $this->data;
}
/**
* {#inheritDoc}
*/
public function getRoles() {
return array('ROLE_OAUTH_USER');
}
}
<?php
namespace Delivve\WebBundle\Service;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use Delivve\WebBundle\Security\WebKeyUserProvider;
class WebKeyUsersService implements UserProviderFactoryInterface, OAuthAwareUserProviderInterface {
public function loadUserByUsername($username) {
throw new Exception('loadByUsername not implemented');
}
public function supportsClass($class) {
return $class === "Delivve\\WebBundle\\Security\\WebKeyUserProvider";
}
public function refreshUser(\Symfony\Component\Security\Core\User\UserInterface $user) {
if (!$this->supportsClass(get_class($user))) {
throw new UnsupportedUserException(sprintf('Unsupported user class "%s"', get_class($user)));
}
return $user;
}
public function loadUserByOAuthUserResponse(UserResponseInterface $response) {
return new OAuthUser($response);
}
public function create(ContainerBuilder $container, $id, $config)
{
// TODO: Implement create() method.
}
public function getKey()
{
// TODO: Implement getKey() method.
}
public function addConfiguration(NodeDefinition $builder)
{
// TODO: Implement addConfiguration() method.
}
}
And these are my configurations:
routingSecurityOAuth.yml
hwi_oauth_login:
resource: "#HWIOAuthBundle/Resources/config/routing/login.xml"
prefix: /login
hwi_oauth_redirect:
resource: "#HWIOAuthBundle/Resources/config/routing/redirect.xml"
prefix: /connect
facebook_login:
pattern: /login/check-facebook
google_login:
pattern: /login/check-google
web_target:
pattern: /target
defaults: { _controller: DelivveWebBundle:Security:oauthTarget }
service
services:
web_key_user_provider:
class: Delivve\WebBundle\Service\WebKeyUsersService
security
security:
providers:
web_key_user_provider:
id: web_key_user_provider
firewalls:
web_key:
pattern: ^/web/*
anonymous: ~
provider: web_key_user_provider
oauth:
resource_owners:
facebook: "/web/login/check-facebook"
google: "/web/login/check-google"
# linkedin: "/web/login/check-linkedin"
login_path: /web/login
failure_path: /web/login
check_path: /web/login_check
default_target_path: /web/target
oauth_user_provider:
service: web_key_user_provider
default:
anonymous: ~
access_control:
- { path: ˆ/web/target, roles: ROLE_OAUTH_USER }
- { path: ˆ/web/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
routing
web_key_register:
pattern: /webRegister
defaults: { _controller: DelivveWebBundle:Security:webRegister }
web_key:
resource: "#DelivveWebBundle/Resources/config/routingSecurityOAuth.yml"
prefix: /web/
config
hwi_oauth:
firewall_name: web_key
resource_owners:
facebook:
type: facebook
client_id: %facebook_client_id%
client_secret: %facebook_client_secret%
scope: email
infos_url: "https://graph.facebook.com/me?fields=username,name,email,picture.type(large)"
paths:
email: email
profilepicture: picture.data.url
options:
display: popup
google:
type: google
client_id: %google_client_id%
client_secret: %google_client_secret%
scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
paths:
email: email
profilepicture: picture

Categories