symfony2 CLI [Symfony\Component\Debug\Exception\ContextErrorException] - php

I'm having a problem whilst trying to create a command with Symfony2's Console component, in a full Symfony stack app.
If i try to pass my services in via DI, the command throws the following error when i try to run it:
[Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Trying to get property of non-object
If I create the command with ContainerAwareCommand and try to get my service with
$this->getContainer()->get('mtgu.api.card.list.response.data');
I get
[LogicException]
The container cannot be retrieved as the application instance is not yet set.
My service is defiantly being loaded, as its used in a front end controller. This problem gets stranger, as if I pass a repository service - I don't get this problem!
Is there some trick to setting up a service to be passible by this? Or have I messed up my configuration somehow?
Im "autoloading" all my services by doing this in my DI Extension rather than including them all through the the main services.yml. I thought this or the ordering of the yml includes maybe effecting it - but I have tried manually including everything but still no joy!
$finder = new Finder();
$finder->name('services.yml');
/**
* #var $file SplFileInfo
*/
foreach($finder->in(__DIR__.'/../') as $file) {
$loader = new Loader\YamlFileLoader($container, new FileLocator($file->getPath()));
$loader->load('services.yml');
}
Vendor/Bundle/Command/services.yml
services:
mtgu.command.slugify:
class: MightyStudios\MtguBundle\Command\SlugifyCommand
tags:
- { name: console.command }
arguments:
- #mtgu.api.card.list.response.data
I think this maybe just some config issue, but Google has failed me to find the answer! Has anyone else run into this problem and can they shed any light!?
Many thanks

A better structure would be to put your services files in the Resources/config directory of your bundle (See also all core bundles). However, that's aside.
The problem is described by the exception: The container cannot be retrieved as the application instance is not yet set. Which is thrown in the ContainerAwareCommand#getContainer() method when $this->application is null. The application is set in the first line of the Application#add() method.
This means that you call $this->getContainer() before you add the command to the application. Maybe you use it in your constructor?
If so, remove it and only use the container in Command#execute(), Command#interact() or Command#initialize().

Related

autowire Predis Interface in symfony

i wanna use ClientInterface in my class constructor and i give an error :
Cannot autowire service "App\Service\DelayReportService": argument "$client" of method "__construct()" references interface "Predis\ClientInterface" but no such service exists. Did you create a class that implements this interface?
seems to be i should add it manually to services.yml i added it like :
Predis\ClientInterface: '#Predis\Client'
and now i give this error:
You have requested a non-existent service "Predis\Client".
what is the solution and why symfony itself dont handle it?
you seem to be confused about how to define a service... which isn't surprising tbh
look here
https://symfony.com/doc/5.4/service_container.html#explicitly-configuring-services-and-arguments
for example
services:
App\Service\Concerns\IDevJobService:
class: App\Tests\Service\TestDevJobService
autowire: true
public: true
where
IDevJobService is an INTERFACE
and
TestDevJobService
is the actual implementation that will be auto injected
using # inside the yaml files is done to reference a service that has already been defined ELSEWHERE
https://symfony.com/doc/5.4/service_container.html#service-parameters
you probably want to watch symfonycasts services tutorial (I am not affiliated and I havent watched it myself yet (sure wish I did)).
EDIT
Predis\Client is a 3rd party class. It isn't in your App namespace or in your src folder. Symfony checks the src folder for class that it will then make to a service. See services.yaml there is a comment there, look for exclude and resource. And I'm not sure, even if you autoload it, that you can then just do #Predis\Client to reference an existing service.
be sure as well to debug your config using
php bin/console debug:autowiring
under linux you could do as well php bin/console debug:autowiring | grep Predis to find it more quickly (if it is there at all)

Laravel Dusk - Class config does not exist

recently upgraded a 5.3 project to 5.4 and all seemed good.
Today I started to implement Dusk however had hit an issue when running the example test
☁ footy-finance [5.4] ⚡ php artisan dusk
PHPUnit 6.0.0 by Sebastian Bergmann and contributors.
E 1 / 1 (100%)
Time: 162 ms, Memory: 6.00MB
There was 1 error:
1) Tests\Browser\ExampleTest::testBasicExample
ReflectionException: Class config does not exist
/Users/owen/Sites/footy-finance/vendor/laravel/framework/src/Illuminate/Container/Container.php:681
/Users/owen/Sites/footy-finance/vendor/laravel/framework/src/Illuminate/Container/Container.php:565
/Users/owen/Sites/footy-finance/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:105
/Users/owen/Sites/footy-finance/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:263
/Users/owen/Sites/footy-finance/vendor/laravel/dusk/src/TestCase.php:203
/Users/owen/Sites/footy-finance/vendor/laravel/dusk/src/TestCase.php:40
I've had a look at line 40 of TestCase.php and its
public function baseUrl()
{
return config('app.url');
}
So it does look like something to do with the global config helper anybody have any ideas?
I'm running
PHP 7.0.14
Laravel/Framework 5.4.8
Laravel/Dusk 1.0.5
The full composer.lock can be seen https://gist.github.com/OwenMelbz/c05172b33f6eb4483e37a56469b53722
Fingers crossed you guys have some ideas!
Cheers :)
I had this error in the log
Class config does not exist
the problem with me was that in the .env file I had set a configuration variable in the following way:
APP_NAME=Application Name
note the space. When I changed it to this:
APP_NAME="Application Name"
the problem got fixed
The issue is with .env file
App_Name
in the original file its written this way>>> APP_NAME=Application Name
Make it like this APP_NAME="Application Name"
In my case, this solution works:
1) Remove all contents of the bootstrap/cache folder
2) Run the composer dump command
For anybody else who has had this issue.
I had prefer stable set in the composer file, which installed PHPUnit 6.
This was "made stable today" - thus it installed during a composer update.
Downgrading to PHPUnit 5 fixes the issue - so was bad timing starting it today.
I just ran into the the same issue, in my case the .env was all clean, no unwrapped empty spaces.
This error message can also occur when writting/debugging a test case, using the setup() method in that test, forgetting to call parent::setup() as the first statement in that function.
protected $stuf;
function setup() {
parent::setup();
$this->stuf = 'stuf';
}
I found very useful info here on what else could happen when you're getting this error message.
I've also had this issue. For me it was caused by calling the config() function inside a dataProvider method. DataProviders are called before the createApplication() method initialises the application, and populates the DI container. Hence config() fails because the app('config') call in the helper function can't resolve the config class from the container.
I'm very late for the party here but for anyone experiencing the same issue with Laravel's unit test and none of the above solutions work, you can look into mine and see if this might help.
In my case, I was trying to call a method that will remove all the test keys that persisted in my Redis database when I run the unit test. The method is called in the tearDown method of the class. The error occurs because the parent constructor is called before the actual tearDown code is executed. That's the reason why I'm having the error.
Instead of this one......
/**
* tearDown is executed after test stub
*/
protected function tearDown()
{
parent::tearDown();
$this->deleteTestKeys();
}
Change it to this one...
protected function tearDown()
{
$this->deleteTestKeys();
parent::tearDown();
}
In this case, the class' is not totally destroyed yet and the Laravel's config method will get called accordingly.
I had this in a Lumen application today. After some investigation and playing around, I found that it was because in PHPStorm it was adding the --no-configuration option onto the phpunit command because I hadn't configured my PHPUnit setup for the project in the IDE.
I corrected that by clicking 'Run > Edit Configurations' and then under 'Defaults > PHPUnit' click the little button to the far right of the 'Use alternative configuration file:' option and set the 'Default configuration file:' to the full path to your project's phpunit.xml.
Hope this helps!
I saw this error after following some dodgy installation instructions for a third party module, which said to register a service provider in bootstrap/app.php
$app->singleton(...);
$app->singleton(...);
$app->register(\Third\Party\ServiceProvider::class);
This caused $this->app['config'] to generate the error BindingResolutionException: Target class [config] does not exist.
I fixed it by putting it in config/app.php, where it belongs:
/*
* Package Service Providers...
*/
Third\Party\ServiceProvider::class,

using ckeditor in symfony3

I try to use ckeditor in symfony3, I successfully installed it but get an error when I try to us it in my form as described in tutorial (https://symfony.com/doc/current/bundles/IvoryCKEditorBundle/index.html):
$builder->add('content', CKEditorType::class);
but that produces this error:
Type error: Argument 1 passed to
Ivory\CKEditorBundle\Form\Type\CKEditorType::__construct() must be an
instance of Ivory\CKEditorBundle\Model\ConfigManagerInterface, none
given
it looks like, there is a problem because a FormType should not demand params in its constructor, am I wrong?
I had the same error and solved it by adding CKEditorBundle to AppKernel.
This was stated in the comments of CountZero's answer. You can find IvoryCKEditorBundle installation notes here.
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Ivory\CKEditorBundle\IvoryCKEditorBundle(),
// ...
);
// ...
}
}
There are no bugs in IvoryCKEditorBundle. If you provide your composer.json, results of commands bin/console debug:container and bin/console config IvoryCKEditorBundle it'll really help me to give you more precise answer.
it looks like, there is a problem because a FormType should not demand params in its constructor, am I wrong?
You are wrong, CKEditorType may demand params in its constructor, and it does so in the current version.
There's something wrong with file vendor/egeloen/ckeditor-bundle/Resources/config/form.xml
It should configure (provide) service dependencies for CKEditorBundle, but it doesn't.
I would try to update composer, clear cache and debug service container configuration for this bundle, it should look like this:
⇒ composer update
⇒ bin/console cache:clear
⇒ bin/console debug:container|grep ivory
ivory_ck_editor.config_manager Ivory\CKEditorBundle\Model\ConfigManager
ivory_ck_editor.form.type Ivory\CKEditorBundle\Form\Type\CKEditorType
ivory_ck_editor.plugin_manager Ivory\CKEditorBundle\Model\PluginManager
ivory_ck_editor.renderer Ivory\CKEditorBundle\Renderer\CKEditorRenderer
ivory_ck_editor.styles_set_manager Ivory\CKEditorBundle\Model\StylesSetManager
ivory_ck_editor.template_manager Ivory\CKEditorBundle\Model\TemplateManager
ivory_ck_editor.twig_extension Ivory\CKEditorBundle\Twig\CKEditorExtension

Creating a new ServiceProvider / Facade as a package in Laravel 5

Introduction
I've never worked with a framework before (Zend, CakePHP, etc) and finally decided to sit down and learn one. I'm starting with Laravel because the code looks pretty and unlike some other frameworks I tried to install, the "Hello, World!" example worked on the first try.
The Goal
For the time being, I want my app to do something very simple:
User submits a request in the form of: GET /dist/lat,lng
The app uses the remote IP address and MaxMind to determine $latitude1 and $longitude1
This request path is parsed for $latitude2 and $longitude2
Using these two positions, we calculate the distance between them. To do this I'm using Rafael Fragoso's WorldDistance PHP class
Since I plan to re-use this function in later projects, it didn't seem right to throw all of the code into the /app directory. The two reusable parts of the application were:
A service provider that connects to MaxMind and returns a latitude and longitude
A service provider that takes two points on a globe and returns the distance
If I build facades correctly then instead of my routes.php file being a mess of closures within closures, I can simply write:
Route::get('dist/{input}', function($input){
$input = explode( "," , $input );
return Distance::getDistance( GeoIP::getLocation(), $input );
});
What I've tried
Initial Attempt
For the first service provider, I found Daniel Stainback's Laravel 5 GeoIP service provider. It didn't install as easily as it should have (I had to manually copy geoip.php to the /config directory, update /config/app.php by hand, and run composer update and php artisan optimize) however it worked: A request to GET /test returned all of my information.
For the second service provider, I started by trying to mimic the directory structure and file naming convention of the GeoIP service provider. I figured that if I had the same naming convention, the autoloader would be able to locate my class. So I created /vendor/stevendesu/worlddistance/src/Stevendesu/WorldDistance\WorldDistanceServiceProvider.php:
<?php namespace Stevendesu\WorldDistance;
use Illuminate\Support\ServiceProvider;
class WorldDistanceServiceProvider extends ServiceProvider {
protected $defer = false;
public function register()
{
// Register providers.
$this->app['distance'] = $this->app->share(function($app)
{
return new WorldDistance();
});
}
public function provides()
{
return ['distance'];
}
}
I then added this to my /config/app.php:
'Stevendesu\WorldDistance\WorldDistanceServiceProvider',
This fails with a fatal error:
FatalErrorException in ProviderRepository.php line 150:
Class 'Stevendesu\WorldDistance\WorldDistanceServiceProvider' not found
Using WorkBench
Since this utterly failed I figured that there must be some other file dependency: maybe without composer.json or without a README it gives up. I don't know. So I started to look into package creation. Several Google searches for "create package laravel 5" proved fruitless. Either:
They were using Laravel 4.2, in which case the advice was "run php artisan workbench vendor/package --resources"
Or
They were using Laravel 5, in which case the docs were completely useless
The official Laravel 5 docs give you plenty of sample code, saying things like:
All you need to do is tell Laravel where the views for a given namespace are located. For example, if your package is named "courier", you might add the following to your service provider's boot method:
public function boot()
{
$this->loadViewsFrom(__DIR__.'/path/to/views', 'courier');
}
This makes the assumption that you have a service provider to put a boot method in
Nothing in the docs says how to create a service provider in such a way that it will actually be loaded by Laravel.
I also found several different resources all of which assume you have a repository and you just want to include it in your app, or assume you have "workbench". Nothing about creating a new package entirely from scratch.
PHP Artisan did not even have a "workbench" command, and there was no "workbench.php" file in /config, so anything I found related to workbench was worthless. I started doing some research on Workbench and found several different questions on StackOverflow.
After a long time and some experimentation, I managed to get laravel/workbench into my composer.json, composer update, composer install, manually build a workbench.php config file, and finally use the PHP Artisan Workbench command to make a new package:
php artisan workbench Stevendesu/WorldDistance --resources
This created a directory: /workbench/stevendesu/world-distance with a number of sub-directories and only one file: /workbench/stevendesu/world-distance/src/Stevendesu/WorldDistance/WorldDistanceServiceProvider.php
This service provider class looked essentially identical to the file I created before, except that it was in the /workbench directory instead of the /vendor directory. I tried reloading the page and I still got the fatal error:
FatalErrorException in ProviderRepository.php line 150:
Class 'Stevendesu\WorldDistance\WorldDistanceServiceProvider' not found
I also tried php artisan vendor:publish. I don't really know what this command does and the description wasn't helpful, so maybe it would help? It didn't.
Question
How do I create a new service provider as a package so that in future projects I can simply include this package and have all the same functionality? Or rather, what did I do wrong so that the package I created isn't working?
After two days of playing with this I managed to find the solution. I had assumed that the directory structure mapped directly to the autoloader's path that it checked (e.g. attempting to access a class Stevendesu\WorldDistance\WorldDistanceServiceProvider would look in vendor/stevendesu/world-distance/WorldDistanceServiceProvider)... This isn't the case.
Reading through the composer source code to see how it actually loads the files, it builds a "classmap" - essentially a gigantic array mapping classes to their respective files. This file is built when you run composer update or composer install - and it will only be built correctly if composer knows the details of your package. That is - if your package is included in your project's composer.json file
I created a local git repository outside of my app then added my package to my app's composer.json file then ran composer update -- suddenly everything worked perfectly.
As for the:
It didn't install as easily as it should have
the secret sauce here was first add the service provider to /config/app.php then, second run php artisan vendor:publish

Unknown method SfGuardUserTable::retrieveByUsername Symfony1.4

I'm wondering why I got this error when installing sfDoctrineGuard plugin in symfony 1.4 project
stack trace:
SF_ROOT_DIR/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Table.php line 2856 ...
return call_user_func_array(array($this->getRecordInstance(), $method . 'TableProxy'), $arguments);
} catch (Doctrine_Record_UnknownPropertyException $e) {}
throw new Doctrine_Table_Exception(sprintf('Unknown method %s::%s', get_class($this), $method));
}
}
The problem occurs when you run doctrine build all or build model command from the command line.
If the sf_guard_user table exists in your database, running either of these commands generates an empty SfGuardUserTable class in your \lib\model folder and this gets used instead of the sfGuardUserTable class sitting in your plugin folder, which does contain a retrieveByUsername method.
Removing the SfGuard____ classes from inside your lib folder would fix the problem.
I used the build commands quite often and got a bit fed up with doing this each time. I eventually moved the code from within the plugin folder into the lib directory which isn't really recommended. But I don't think the sfGuardUser plugin is maintained any more, so if you know what you're doing you could give it a try.

Categories