Zend\Permissions\Rbac\Role Error 500 when try to instantiate object - zend-framework3

I'm trying to implement a RBAC in my project, but I can't instantiate Rbac class.
My code:
<?php
namespace Login\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Permissions\Rbac\Rbac;
use Zend\Permissions\Rbac\Role;
class TesteController extends AbstractActionController {
public function indexAction() {
$role = new Role('teste');
die('=== FIM ===');
}
}
When I comment the Role line it shows "=== FIM ===", but when it isn't commented it gives 500 error.
I already check the module struct in vendor and it's alright.
Do I need to do anything else when I install a vendor module via composer to zend 3 recognize it?

The error was cause by my php version that doesn't accept return type declarations. The Rbac module is full of it.

Related

Load Symfony (5.2) config from database

I am a newbie in Symfony but I know how to use OOP in PHP.
I try (with frustration) to couple custom parameters with Symfony configs by using Doctrine entities.
To solve the problem I used for e.g. the answer from Michael Sivolobov: https://stackoverflow.com/a/28726681/2114615 and other sources.
My solution:
Step 1: Create new package in config folder
-> config
-> packages
-> project
-> services.yaml
-> project
-> src
-> ParameterLoaderBundle.php
-> DependencyInjection
-> Compiler
-> ParameterLoaderPass.php
Step 2: Import the new resource
# config/services.yaml
...
imports:
- { resource: 'packages/project/config/services.yaml' }
...
Step 3: Package coding
# packages/project/config/services.yaml
services:
Project\:
resource: "../src"
<?php
namespace Project;
use Project\DependencyInjection\Compiler\ParameterLoaderPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ParameterLoaderBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ParameterLoaderPass(), PassConfig::TYPE_AFTER_REMOVING);
}
}
<?php
namespace Project\DependencyInjection\Compiler;
use App\Entity\SettingCategory;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class ParameterLoaderPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$em = $container->get('doctrine.orm.default_entity_manager');
$setting = $em->getRepository(SettingCategory::class)->findAll();
$container->setParameter('test', $setting);
}
}
After at all I test the new Parameter in my API controller:
$this->getParameter('Test');
But the following error message appears:
The parameter \"test\" must be defined.
Couple of things going on here. First off, loading config from a database is very unusual in Symfony so it is not surprising that you are having difficulty. Secondly, your process code is never getting called. Part of debugging is making sure that code that you expect to be called is in fact being called. Third, you really got off on a tangent with attempting to add a bundle under config. Way back in Symfony 2 there used to be more bundle related stuff under app/config and it may be that you discovered some old articles and misunderstood them.
But, the big problem here is that Symfony has what is known as a 'compile' phase which basically processes all the configuration and caches it. Hence the CompilerPassInterface. Unfortunately, services themselves are not available during the compile phase. They simply don't exist yet so no entity manager. You need to open your own database connection if you really want to load config from a database. You will want to use just a database connection object and not the entity manager since part of the compile phase is to process the entities themselves.
So get rid of all your code and just adjust your Kernel class:
# src/Kernel.php
class Kernel extends BaseKernel implements CompilerPassInterface
{
use MicroKernelTrait;
public function process(ContainerBuilder $container)
{
$url = $_ENV['DATABASE_URL'];
$conn = DriverManager::getConnection(['url' => $url]);
$settings = $conn->executeQuery('SELECT * FROM settings')->fetchAllAssociative();
$container->setParameter('test',$settings);
}
And be aware that even if you get all this working, you will need to manually rebuild the Symfony cache after updating your settings table. It is not going to be automatic. You really might consider taking a completely different approach.

symfony 3.1 Check if a bundle is installed

I'm developing a bundle who has a dependency on another one.
In order to handle the case that the base bundle has not been installed I'll like to perform a "bundle_exists()" function inside a controller.
The question is: How can I have a list of installed bundles or How can I check for the name (eventually also the version) of a bundle.
Thanks.
In addition to #Rooneyl's answer:
The best place to do such a check is inside your DI extension (e.g. AcmeDemoExtension). This is executed once the container is build and dumped to cache. There is no need to check such thing on each request (the container doesn't change while it's cached anyway), it'll only slow down your cache.
// ...
class AcmeDemoExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$bundles = $container->getParameter('bundles');
if (!isset($bundles['YourDependentBundle'])) {
throw new \InvalidArgumentException(
'The bundle ... needs to be registered in order to use AcmeDemoBundle.'
);
}
}
}
Your class needs to have access to the container object (either by extending or DI).
Then you can do;
$this->container->getParameter('kernel.bundles');
This will give you a list of bundles installed.
Update;
If you are in a controller that extends the Symfony\Bundle\FrameworkBundle\Controller\Controller or in a command class that extends Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand, you can just get the parameter.
$this->getParameter('kernel.bundles').
Else #Wouter J's answer is your best answer.
You can get a list of all Bundles from the Kernel like this:
public function indexAction ()
{
$arrBundles = $this->get("kernel")->getBundles();
if (!array_key_exists("MyBundle", $arrBundles))
{
// bundle not found
}
}
From Andrey at this question: How do I get a list of bundles in symfony2?
If you want to call a non static method of registered bundle object (not class) then you can do the following:
$kernel = $this->container->get('kernel');
$bundles = $kernel->getBundles();
$bundles['YourBundleName']->someMethod();
Where 'YourBundleName' is the name of your bundle, which you can get by calling from console:
php app/console config:dump-reference

Symfony 2.5.6 error InvalidArgumentException: The service definition "event_dispatcher" does not exist

I'm trying to build my first Compiler Pass in Symfony 2. For now, I'm just trying to get the core event_dispatcher service from FrameWorkBundle inside a SampleBundle, but I get this error :
error InvalidArgumentException: The service definition "event_dispatcher" does not exist.
Here is the code for my compiler :
<?php
namespace Me\SampleBunlde\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class RegisterListenersPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('event_dispatcher');
}
}
?>
I'm a bit surprised since I'm following step by step a professionnal Symfony book who assures me that I will find this service with that id.
I've done some researches about that, and I discovered that only the debug.event_dispatcher service was avaible. Then I checked for aliases and saw that there was a private Alias named 'event_dispatcher' pointing to debug.event_dispatcher. So I'm really confused about all that. And I'm wondering :
Why is the Alias private ? Do I need to set him Public or is it the wrong way ?
Why Symfony does not automatically interprets my event_dispatcher call ?
Thank you for your help !
Use findDefinition() instead of getDefinition(). findDefinition also looks for aliases.

symfony 2.3 error: autoloader find file but not class

First, sorry if my english it's not so good.
I readed a lot of questions like the one i have, but any solution works.
The question is that I'm developing a porject in Symfony 2.3, yes, i'm beginner using it...
I've created a 'Userbundle', and i want to display the info profile of an user.
When I access to the correct URL I have the famous message error:
"The autoloader expected class "Mylife\UserBundle\Entity\UserRepository" to be defined in file "D:\www\Symfony/src\Mylife\UserBundle\Entity\UserRepository.php". The file was found but the class was not in it, the class name or namespace probably has a typo."
That's my default controller code:
namespace Mylife\UserBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Mylife\UserBundle\Entity\User;
use Mylife\UserBundle\Form\Frontend\RegisterType;
class DefaultController extends Controller
{
public function profileAction(){
$user_id=1;
$em=$this->getDoctrine()->getEntityManager();
$profile=$em->getRepository('UserBundle:User')
->findProfile($user_id);
return $this->render('UserBundle:Default:profile.html.twig', array( 'profile' => $profile));
}
And my UserRepository.php code:
// src/Mylife/UserBundle/Entity/UserRepository.php
namespace Mylife\UserBundle\Entity;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function findProfile($user)
{
$em = $this->getEntityManager();
$consult= $em->createQuery('
SELECT u, nk, n
FROM UserBundle:User u
WHERE u.user= :id');
$consult->setParameter('id', $user);
return $consult->getResult();
}
}
I have the same problem when trying to use a form class in the same bundle, but i no see any error in namesapce or class name.
The project structure is:
-src
-Mylife
-UserBundle
....
-Entity
...
-User.php
-UserRepository.php
I'm going mad trying to solve the problem and reading a lot of forums and examples.
I've tryed to dissable APC, to restart Apache, erase the cache, and nothing of this worked.
Thanks a lot!!
Carlos
PD: I'm not sure why appears a piece of code at the top of the error page and why it begins in "getEntityMAnager();..." row... Why is not showing the text code before it?. Image:http://es.tinypic.com?ref=r0s8k5
IMPORTANT: When I generated the entity USer by console, I say "no" when asked to generate repository. May be this is the problem. Any suggestion now?
Thanks again
Try to add this comment in your User entity file:
/**
*
* #ORM\Entity(repositoryClass="YourProject\UserBundle\Entity\UserRepository")
*/
class User
{
...
}
or something like this:
custom repository class in symfony2
Found it!!
It's was a silly mistake. I've began the PHP repository file with
<?
...
and must be
<?php
...
Sorry at all!

Symfony2 custom console command not working

I created a new Class in src/MaintenanceBundle/Command, named it GreetCommand.php and put the following code in it:
<?php
namespace SK2\MaintenanceBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class GreetCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('maintenance:greet')
->setDescription('Greet someone')
->addArgument('name', InputArgument::OPTIONAL, 'Who do you want to greet?')
->addOption('yell', null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
if ($name) {
$text = 'Hello '.$name;
} else {
$text = 'Hello';
}
if ($input->getOption('yell')) {
$text = strtoupper($text);
}
$output->writeln($text);
}
}
?>
And tried to call it via
app/console maintenance:greet Fabien
But i always get the following error:
[InvalidArgumentException]
There are no commands defined in the "maintenance" namespace.
Any ideas?
I had this problem, and it was because the name of my PHP class and file didn't end with Command.
Symfony will automatically register commands which end with Command and are in the Command directory of a bundle. If you'd like to manually register your command, this cookbook entry may help: http://symfony.com/doc/current/cookbook/console/commands_as_services.html
I had a similar problem and figured out another possible solution:
If you override the default __construct method the Command will not be auto-registered by Symfony, so you have to either take the service approach as mentioned earlier or remove the __construct override and make that init step in the execute method or in the configure method.
Does actually anyone know a good best practice how to do init "stuff" in Symfony commands?
It took me a moment to figure this out.
I figured out why it was not working: I simply forgot to register the Bundle in the AppKernel.php. However, the other proposed answers are relevant and might be helpful to resolve other situations!
By convention: the commands files need to reside in a bundle's command directory and have a name ending with Command.
in AppKernel.php
public function registerBundles()
{
$bundles = [
...
new MaintenanceBundle\MaintenanceBundle(),
];
return $bundles;
}
In addition to MonocroM's answer, I had the same issue with my command and was silently ignored by Symfony only because my command's constructor had 1 required argument.
I just removed it and call the parent __construct() method (Symfony 2.7) and it worked well ;)
If you are over-riding the command constructor and are using lazy-loading/autowiring, then your commands will not be automatically registered. To fix this you can add a $defaultName variable:
class SunshineCommand extends Command
{
protected static $defaultName = 'app:sunshine';
// ...
}
Link to the Symfony docs.
I think you have to call parent::configure() in your configure method
I had this same error when I tried to test my command execution with PHPUnit.
This was due to a wrong class import :
use Symfony\Component\Console\Application;
should be
use Symfony\Bundle\FrameworkBundle\Console\Application;
cf. Other stack thread
In my case it was complaining about the "workflow" namespace although the WorkflowDumpCommand was correctly provided by the framework.
However, it was not available to run because I have not defined any workflows so the isEnabled() method of the command returned false.
I tried to use a service passed via constructor inside the configure method:
class SomeCommand extends Command {
private $service;
public function __construct(SomeService $service) {
$this->service = $service;
}
protected function configure(): void {
$this->service->doSomething(); // DOES NOT WORK
}
}
Symfony uses Autoconfiguration that automatically inject dependencies into your services and register your services as Command, event,....
So first just make sure that you have services.yaml in your config folder. with autoconfigure:true.
this is the default setting
Then Make sure That All your files are exactly the same name as Your Class.
so if you have SimpleClass your file must be SimpleClass.php
If you have a problem because of a __constructor,
go to services.yml and add something like this:
app.email_handler_command:
class: AppBundle\Command\EmailHandlerCommand
arguments:
- '#doctrine.orm.entity_manager'
- '#app.email_handler_service'
tags:
- { name: console.command }
For newer Symfony-Version (5+) commands must be registered as services.
What I do frequently forget while setting it up, is to tag it properly:
<service id="someServiceCommand">
<tag name="console.command"/>
</service>
Without this litte adaptation, your command name will not be displayed and therefore not accessible.

Resources