I'm using sumfony 3.3.10, I have installed a fresh project of symfony and I added knpMenuBundle using this command,
composer require knplabs/knp-menu-bundle "^2.0"
Now I followed everything exactly as mentioned here http://symfony.com/doc/master/bundles/KnpMenuBundle/menu_builder_service.html
and added this line {{ knp_menu_render('main') }} in default/index.html.twig file.
Now when I execute the project, its showing me this error,
[InvalidArgumentException]
Menu builder services must be public but "app.menu_builder" is a private service.
config.yml
knp_menu:
# use "twig: false" to disable the Twig extension and the TwigRenderer
twig:
template: KnpMenuBundle::menu.html.twig
# if true, enables the helper for PHP templates
templating: false
# the renderer to use, list is also available by default
default_renderer: twig
MenuBuilder.php
<?php
namespace AppBundle\Menu;
use Knp\Menu\FactoryInterface;
class MenuBuilder
{
private $factory;
/**
* #param FactoryInterface $factory
*
* Add any other dependency you need
*/
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
public function createMainMenu(array $options)
{
$menu = $this->factory->createItem('root');
$menu->addChild('Home', array('route' => 'homepage'));
// ... add more children
return $menu;
}
}
services.yml
app.menu_builder:
class: AppBundle\Menu\MenuBuilder
arguments: ["#knp_menu.factory"]
tags:
- { name: knp_menu.menu_builder, method: createMainMenu, alias: main } # The alias is what is used to retrieve the menu
How can I resolve it. Any help is much appreciated. Thanks
I added public: true to the app.menu_builder service in services.php,
app.menu_builder:
class: AppBundle\Menu\MenuBuilder
public: true
arguments: ["#knp_menu.factory"]
tags:
- { name: knp_menu.menu_builder, method: createMainMenu, alias: main } # The alias is what is used to retrieve the menu
And everything is working fine now.
Refer : https://symfony.com/doc/current/service_container/alias_private.html#marking-services-as-public-private
Related
I created a service to extend the menu in admin of Sylius. It's work well ;)
I follow the official doc
I try to inject the router service in, but I've this following error :
Type error: Too few arguments to function
XXMenuListener::__construct(), 0 passed in
appDevDebugProjectContainer.php on line 1542 and exactly 1 expected
The declaration of this service :
services:
app.listener.admin.menu_builder:
class: XXX\Menu\AdminMenuListener
autowire: true
arguments:
- '#router'
tags:
- { name: kernel.event_listener, event: sylius.menu.admin.main, method: addAdminMenuItems }
and the service himself :
<?php
namespace XXX\Menu;
use Sylius\Bundle\UiBundle\Menu\Event\MenuBuilderEvent;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
final class AdminMenuListener
{
private $router;
public function __construct(Router $router){
$this->router = $router;
}
/**
* #param MenuBuilderEvent $event
*/
public function addAdminMenuItems(MenuBuilderEvent $event){
$menu = $event->getMenu();
$newSubmenu = $menu
->addChild('new')
->setLabel('XXX')
;
$newSubmenu
->addChild('new-subitem')
->setLabel('XXX')
//->setUri('https://www.google.com');
->setUri($this->router->generate('foo'))
;
}
}
What is wrong in ? Thanks for your help!
I think you need to clear cache if not helped to clean the cache directory manually.
In any case, you don't need a router service because menubuilder already has it.
For example:
for uri
$newSubmenu
->addChild('new-subitem')
->setLabel('XXX')
->setUri('https://www.google.com')
;
for route
$newSubmenu
->addChild('new-subitem', ['route' => 'foo'])
->setLabel('XXX')
;
If you use autowire to true you don't need to specify the router service. Something like this should be enough :
services:
app.listener.admin.menu_builder:
class: XXX\Menu\AdminMenuListener
autowire: true
tags:
- { name: kernel.event_listener, event: sylius.menu.admin.main, method: addAdminMenuItems }
In any case, your error indicates that you don't have any arguments. May be it's a caching issue or may be you have another service declaration for the same class XXX\Menu\AdminMenuListener without autowire to true and without arguments.
I am trying to call Twig function created in TwigExtension (Symfony 3.3). Problem is that I can't find what I did wrong and I am not sure why it is not working
Does someone knows where is the problem?
This is error I am getting:
Unknown "getCurrentLocale" function.
Here is my code:
Twig Extension:
<?php
namespace AppBundle\Extension;
use Symfony\Component\HttpFoundation\Request;
class AppTwigExtensions extends \Twig_Extension
{
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('getCurrentLocale', [$this, 'getCurrentLocale']),
];
}
public function getCurrentLocale()
{
dump ($this->request);
/*
* Some code
*/
return "EN";
}
public function getName()
{
return 'App Twig Repository';
}
}
Services:
services:
twig.extension:
class: AppBundle\Extension\AppTwigExtensions
arguments: ["#request"]
tags:
- { name: twig.extension }
Twig:
{{ attribute(country.country, 'name' ~ getCurrentLocale() ) }}
So what is your overall plan with the extension. Do you still need it when app.request.locale in twig returns the current locale? (which it does)
Also by default the #request service does not exist anymore.
In Symfony 3.0, we will fix the problem once and for all by removing the request service — from New in Symfony 2.4: The Request Stack
This is why you should get something like:
The service "twig.extension" has a dependency on a non-existent service "request".
So you made this service? Is it loaded? What is it? You can see all available services names matching request using bin/console debug:container request.
If you do need the request object in the extension, if you are planning to do more with you would want to inject the request_stack service together with $request = $requestStack->getCurrentRequest();.
Somehow the code, symfony version and the error message you posted don't correlate. Also in my test, once removing the service arguments it worked fine. Try it yourself reduce the footprint and keep it as simple as possible, which in my case was:
services.yml:
twig.extension:
class: AppBundle\Extension\AppTwigExtensions
tags:
- { name: twig.extension }
AppTwigExtensions.php:
namespace AppBundle\Extension;
class AppTwigExtensions extends \Twig_Extension {
public function getFunctions() {
return [
new \Twig_SimpleFunction('getCurrentLocale', function () {
return 'en';
}),
];
}
}
And take it from there, figure out when it goes wrong.
I use a service to get a basic search form on my website. I need to set the action form to a search result page. I can set the form action to be a specific url (/search) but can't use a "generateUrl"-like method in a yaml.
I want to be able to test my form in dev environment /app_dev.php as well as in prod environment. Any suggestion or idea?
services.yml
parameters:
form.search.default.value: "search for things"
services:
app_bundle.form.type.search:
class: AppBundle\Form\SearchType
arguments: [AppBundle\Entity\Search]
tags:
- { name: form.type, alias: tab_search }
app_bundle.form.search:
factory_method: create
factory_service: form.factory
class: Symfony\Component\Form\Form
arguments:
- tab_search
- #app_bundle.form.entity.search
- { action: /search } # I'd like something similar to $this->generateUrl("search")
app_bundle.form.entity.search:
class: AppBundle\Entity\Search
arguments: [%form.search.default.value%]
DefaultController.php
/**
* #Route("/", name="homepage")
* #Template()
*/
public function indexAction(Request $request)
{
$form = $this->get('app_bundle.form.search');
// [...]
return array('search' => $form->createView());
}
Untested, but I've done something like this before with this code:
protected $action;
public function setAction($action)
{
$this->action = $action;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// rest of form configuration
$builder->setAction($this->action);
}
Then in your services.yml:
services:
app_bundle.form.type.search:
class: AppBundle\Form\SearchType
arguments: [AppBundle\Entity\Search]
calls:
- [setAction, ["%app_bundle.form.type.search.action%"]]
tags:
- { name: form.type, alias: tab_search }
And then set the app_bundle.form.type.search.action value in parameters somewhere.
If you want to allow the method to be overridden but set a default, set the action in setDefaultOptions and then override from the controller or a listener.
Error:
...ThemeValidator::__construct() must be of the type array, null given...
For some reason the Service is not being called, but the Class is being loaded directly.
validation.yml
theme:
- NotBlank: ~
- DashboardHub\Bundle\AppBundle\Validator\Constraints\ThemeValidator: ~
Validator Class
<?php
namespace DashboardHub\Bundle\AppBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ThemeValidator extends ConstraintValidator
{
protected $config;
public function __construct(array $config)
{
$this->config = $config;
}
public function validatedBy()
{
return 'theme.validator';
}
public function validate($value, Constraint $constraint)
{
var_dump($this->config); exit;
}
// ...
service.yml
dashboardhub_app_main.validator.constraints.theme:
class: DashboardHub\Bundle\AppBundle\Validator\Constraints\ThemeValidator
arguments: ["%dashboard_hub_app%"]
tags:
- { name: validator.constraint_validator, alias: theme.validator }
Edit
parameters:
dashboard_hub_app:
themes:
Github: DashboardHubAppBundle:Template:Github.html.twig
GithubTravis: DashboardHubAppBundle:Template:GithubTravis.html.twig
Edit2
It works find when used in the Form Service
dashboardhub_app_main.form.type.dashboard:
class: DashboardHub\Bundle\AppBundle\Form\DashboardType
arguments: ["%dashboard_hub_app%"]
tags:
- { name: form.type, alias: dashboard }
parameters:
dashboard_hub_app: -- !!!!! IS NULL yes
funny :)
parameters follow one by one, so you need to be careful, paramenters && themes - are different.
to inject an array you need provide a value for this paramenter, but i guess you need to inject this one
themes:
Github: DashboardHubAppBundle:Template:Github.html.twig
GithubTravis: DashboardHubAppBundle:Template:GithubTravis.html.twig
arguments: ["%themes%"]
and result will be an array inside your Validator class
array (size=2)
'Github' => string 'DashboardHubAppBundle:Template:Github.html.twig' (length=47)
'GithubTravis' => string 'DashboardHubAppBundle:Template:GithubTravis.html.twig' (length=53)
I need to inject two objects into ImageService. One of them is an instance of Repository/ImageRepository, which I get like this:
$image_repository = $container->get('doctrine.odm.mongodb')
->getRepository('MycompanyMainBundle:Image');
So how do I declare that in my services.yml? Here is the service:
namespace Mycompany\MainBundle\Service\Image;
use Doctrine\ODM\MongoDB\DocumentRepository;
class ImageManager {
private $manipulator;
private $repository;
public function __construct(ImageManipulatorInterface $manipulator, DocumentRepository $repository) {
$this->manipulator = $manipulator;
$this->repository = $repository;
}
public function findAll() {
return $this->repository->findAll();
}
public function createThumbnail(ImageInterface $image) {
return $this->manipulator->resize($image->source(), 300, 200);
}
}
Here is a cleaned up solution for those coming from Google like me:
Update: here is the Symfony 2.6 (and up) solution:
services:
myrepository:
class: Doctrine\ORM\EntityRepository
factory: ["#doctrine.orm.entity_manager", getRepository]
arguments:
- MyBundle\Entity\MyClass
myservice:
class: MyBundle\Service\MyService
arguments:
- "#myrepository"
Deprecated solution (Symfony 2.5 and less):
services:
myrepository:
class: Doctrine\ORM\EntityRepository
factory_service: doctrine.orm.entity_manager
factory_method: getRepository
arguments:
- MyBundle\Entity\MyClass
myservice:
class: MyBundle\Service\MyService
arguments:
- "#myrepository"
I found this link and this worked for me:
parameters:
image_repository.class: Mycompany\MainBundle\Repository\ImageRepository
image_repository.factory_argument: 'MycompanyMainBundle:Image'
image_manager.class: Mycompany\MainBundle\Service\Image\ImageManager
image_manipulator.class: Mycompany\MainBundle\Service\Image\ImageManipulator
services:
image_manager:
class: %image_manager.class%
arguments:
- #image_manipulator
- #image_repository
image_repository:
class: %image_repository.class%
factory_service: doctrine.odm.mongodb
factory_method: getRepository
arguments:
- %image_repository.factory_argument%
image_manipulator:
class: %image_manipulator.class%
In case if do not want to define each repository as a service, starting from version 2.4 you can do following, (default is a name of the entity manager):
#=service('doctrine.orm.default_entity_manager').getRepository('MycompanyMainBundle:Image')
Symfony 3.3, 4 and 5 makes this much simpler.
Check my post How to use Repository with Doctrine as Service in Symfony for more general description.
To your code, all you need to do is use composition over inheritance - one of SOLID patterns.
1. Create own repository without direct dependency on Doctrine
<?php
namespace MycompanyMainBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
use MycompanyMainBundle\Entity\Image;
class ImageRepository
{
private $repository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(Image::class);
}
// add desired methods here
public function findAll()
{
return $this->repository->findAll();
}
}
2. Add config registration with PSR-4 based autoregistration
# app/config/services.yml
services:
_defaults:
autowire: true
MycompanyMainBundle\:
resource: ../../src/MycompanyMainBundle
3. Now you can add any dependency anywhere via constructor injection
use MycompanyMainBundle\Repository\ImageRepository;
class ImageService
{
public function __construct(ImageRepository $imageRepository)
{
$this->imageRepository = $imageRepository;
}
}
In my case bases upon #Tomáš Votruba answer and this question I propose the following approaches:
Adapter Approach
Without Inheritance
Create a generic Adapter Class:
namespace AppBundle\Services;
use Doctrine\ORM\EntityManagerInterface;
class RepositoryServiceAdapter
{
private $repository=null;
/**
* #param EntityManagerInterface the Doctrine entity Manager
* #param String $entityName The name of the entity that we will retrieve the repository
*/
public function __construct(EntityManagerInterface $entityManager,$entityName)
{
$this->repository=$entityManager->getRepository($entityName)
}
public function __call($name,$arguments)
{
if(empty($arrguments)){ //No arguments has been passed
$this->repository->$name();
} else {
//#todo: figure out how to pass the parameters
$this->repository->$name(...$argument);
}
}
}
Then foreach entity Define a service, for examplein my case to define a (I use php to define symfony services):
$container->register('ellakcy.db.contact_email',AppBundle\Services\Adapters\RepositoryServiceAdapter::class)
->serArguments([new Reference('doctrine'),AppBundle\Entity\ContactEmail::class]);
With Inheritance
Same step 1 mentioned above
Extend the RepositoryServiceAdapter class for example:
namespace AppBundle\Service\Adapters;
use Doctrine\ORM\EntityManagerInterface;
use AppBundle\Entity\ContactEmail;
class ContactEmailRepositoryServiceAdapter extends RepositoryServiceAdapter
{
public function __construct(EntityManagerInterface $entityManager)
{
parent::__construct($entityManager,ContactEmail::class);
}
}
Register service:
$container->register('ellakcy.db.contact_email',AppBundle\Services\Adapters\RepositoryServiceAdapter::class)
->serArguments([new Reference('doctrine')]);
Either the case you have a good testable way to function tests your database beavior also it aids you on mocking in case you want to unit test your service without the need to worry too much on how to do that. For example, let us suppose we have the following service:
//Namespace definitions etc etc
class MyDummyService
{
public function __construct(RepositoryServiceAdapter $adapter)
{
//Do stuff
}
}
And the RepositoryServiceAdapter adapts the following repository:
//Namespace definitions etc etc
class SomeRepository extends \Doctrine\ORM\EntityRepository
{
public function search($params)
{
//Search Logic
}
}
Testing
So you can easily mock/hardcode/emulate the behavior of the method search defined in SomeRepository by mocking aither the RepositoryServiceAdapter in non-inheritance approach or the ContactEmailRepositoryServiceAdapter in the inheritance one.
The Factory Approach
Alternatively you can define the following factory:
namespace AppBundle\ServiceFactories;
use Doctrine\ORM\EntityManagerInterface;
class RepositoryFactory
{
/**
* #param EntityManagerInterface $entityManager The doctrine entity Manager
* #param String $entityName The name of the entity
* #return Class
*/
public static function repositoryAsAService(EntityManagerInterface $entityManager,$entityName)
{
return $entityManager->getRepository($entityName);
}
}
And then Switch to php service annotation by doing the following:
Place this into a file ./app/config/services.php (for symfony v3.4, . is assumed your ptoject's root)
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
$definition = new Definition();
$definition->setAutowired(true)->setAutoconfigured(true)->setPublic(false);
// $this is a reference to the current loader
$this->registerClasses($definition, 'AppBundle\\', '../../src/AppBundle/*', '../../src/AppBundle/{Entity,Repository,Tests,Interfaces,Services/Adapters/RepositoryServiceAdapter.php}');
$definition->addTag('controller.service_arguments');
$this->registerClasses($definition, 'AppBundle\\Controller\\', '../../src/AppBundle/Controller/*');
And cange the ./app/config/config.yml (. is assumed your ptoject's root)
imports:
- { resource: parameters.yml }
- { resource: security.yml }
#Replace services.yml to services.php
- { resource: services.php }
#Other Configuration
Then you can clace the service as follows (used from my example where I used a Dummy entity named Item):
$container->register(ItemRepository::class,ItemRepository::class)
->setFactory([new Reference(RepositoryFactory::class),'repositoryAsAService'])
->setArguments(['$entityManager'=>new Reference('doctrine.orm.entity_manager'),'$entityName'=>Item::class]);
Also as a generic tip, switching to php service annotation allows you to do trouble-free more advanced service configuration thin one above. For code snippets use a special repository I made using the factory method.
For Symfony 5 it is really simple, without need of services.yml to inject the dependency:
inject the Entity Manager in the service constructor
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
Then get the repository :
$this->em->getRepository(ClassName::class)
by replacing ClassName with your entity name.