I want to create a system of logs in symfony2 and I have a question, so I have in service.yml :
services:
my_logger:
class: Monolog\Logger
arguments: [Debug]
calls:
- [pushHandler, [#my_log_handler]]
my_log_handler:
class: Monolog\Handler\StreamHandler
arguments: [/home/vagrant/Workspace/symfony/app/logs/test.log, 100]
I have a class in Utils/Logs like this :
class Logs {
public static function logInfo($a_log) {
$sc = new ContainerBuilder();
$logguer = $sc->get('my_logger');
$logguer->info($a_log);
}
}
And my controller :
$categories = array();
Logs::logInfo(print_r($categories));
The question is how to modify Utilis/Logs class to be possible to call logInfo method? Help me please...Thx in advance...It's possible to create this?
Related
I would like to access my database that contains all my user inside my provider with doctrine. I followed a tutorial (http://symfony.com/doc/current/security/custom_provider.html) to build my provider for my user, so I have an loadUserByUsername function :
public function loadUserByUsername($username)
{
// make a call to your webservice here
$player = new Player();
$player = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findOneByPseudo($username);
// pretend it returns an array on success, false if there is no user
if ($player) {
return $player;
}
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
);
}
But of course my getDoctrine() function is undefined. So there is something I don't understand with the provider, I am trying to use it to be authenticated when I login so I need a provider, but why I can't search inside my database? How should I write this function? Thank for your help
EDIT :
When I add doctrine by service.yml (and after writting my constructor inside my provider), I have this error :
FatalThrowableError in PlayerProvider.php line 13:
Type error: Argument 1 passed to AppBundle\Security\PlayerProvider::__construct() must be an instance of Doctrine\Bundle\DoctrineBundle\Registry, instance of Doctrine\ORM\EntityManager given, called in /home/jean/PW6/SkA/SkeletonsOnlineV2/skeleton-online/var/cache/dev/appDevDebugProjectContainer.php on line 327
EDIT 2 : When I just put arguments: ['#doctrine'] inside my service.yml, I get an error that says that doctrine is undefined
EDIT 3 : It works now, I just made a dumb mistake
If you read further, it says the following (emphasis mine):
The real implementation of the user provider will probably have some dependencies or configuration options or other services. Add these as arguments in the service definition.
So in your case it would be something like
# app/config/services.yml
services:
app.webservice_user_provider:
class: AppBundle\Security\User\WebserviceUserProvider
arguments: ['#doctrine']
And your class needs a constructor
class WebserviceUserProvider implements UserProviderInterface
{
protected $doctrine;
public function __construct (\Doctrine\Bundle\DoctrineBundle\Registry $doctrine)
{
$this->doctrine = $doctrine;
}
// ...
}
Then in your method replace $this->getDoctrine() with just $this->doctine
I'm using symfony 3.2, i want to have a dynamic database connection, so i 'm importing a file parameters.php in my config.yml file :
imports:
- { resource: parameters.php }
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
In the parameters.php i am defining database_name :
$container->setParameter('database_name', $dbName);
This work fine with native file session, but when i'm using pdo session following the symfony example :
services:
session.handler.pdo:
class: Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
public: false
arguments:
- 'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%'
- { db_username: '%database_user%', db_password: '%database_password%' }
I'have an error on compilation :
[Symfony\Component\DependencyInjection\Exception\RuntimeException]
A string value must be composed of strings and/or numbers, but found parameter "database_name" of type boolean inside string value "mysql:host=%database_host%;port=%database_port%;dbname=%database_name%".
It's like symfony don't know the parameter "database_name".
Can anyone help me ?
OK, it's seems not to be the way to do it ...
Finally i've create a Custom ConnectionFactory
use Doctrine\Bundle\DoctrineBundle\ConnectionFactory;
class MyConnectionFactory extends ConnectionFactory {
public function createConnection(array $params, \Doctrine\DBAL\Configuration $config = null, \Doctrine\Common\EventManager $eventManager = null, array $mappingTypes = array()) {
// Determine here params ....
$params['dbname'] = $dbName;
$params['host'] = $dbHost
$params['user'] = $dbUser
$params['password'] = $dbCode;
return parent::createConnection($params, $config, $eventManager, $mappingTypes);
}
It's work !
Please help me with config Console App, in first - config
#!/usr/bin/env php
<?php
use ....
...
$container = new ContainerBuilder();
$config = new YamlFileLoader($container, new FileLocator(__DIR__));
$config->load('config.yml');
$output = $container->get('symfony.console_output');$logger = $container->get('logger');
//I want automatic injection!!!!
$helloCommand = new HelloCommand($container, $logger);
$application = $container->get('symfony.application');
$application->add($helloCommand);
$application->run(null, $output);
And my config.yml
services:
logger:
class: Symfony\Component\Console\Logger\ConsoleLogger
arguments:
- '#symfony.console_output'
symfony.application:
class: Symfony\Component\Console\Application
calls:
//by this variant autowire not working
- [add, [ '#app.command.hello_command' ]]
- [setDispatcher, ['#symfony.event_dispatcher']]
...
app.command.hello_command:
class: App\Command\HelloCommand
autowire: true
tags:
- { name: console.command }
So my HelloCommand has constructor with ContainerInterface and LoggerInterface and it work only if i set this arguments directly, other i have error about wrong constructor
Or may be exists another way for configuration with config.yml
for only logger - its will be simple by set ['#logger'] as arguments, but how can i set current container as argument?
Or i`ll have to install full symfony with httpkernel (but it does not need)
HelloCommand
http://pastebin.com/VRr3FM7Q
THE DECISION
app.command.hello_command:
class: App\Command\HelloCommand
arguments:
- '#service_container'
- '#logger'
tags:
- { name: console.command }
The problem lies in how you configure your command:
app.command.hello_command:
class: App\Command\HelloCommand
autowire: true
tags:
- { name: console.command }
This misses the 2 constructor arguments required: $container, $logger and is probably why you get the exception. You can add constructor arguments like this:
app.command.hello_command:
class: App\Command\HelloCommand
arguments:
- '#service_container'
- '#logger'
[...]
I'm not sure if the id for the service_container is right. I never pass the container or make things ContainerAware, but you get the general idea. ;)
I'm following this Drupal 8 module development 101 tutorial. It's between 37:15 to 45:14 on the YouTube video. I kept getting this error:
Fatal error: Class 'Drupal\dino_roar\DinoServices\HelloGenerator' not found in C:\Users\myName\Sites\devdesktop\drupal-8.0.5\modules\dino_roar\src\Controller\RoarController.php on line 11
Folder structure:
HelloGenerator.php
<?php
namespace Drupal\dino_roar\DinoServices;
class HelloGenerator
{
public function getHello($count){
return "Gotten Hello ".$count;
}
}
RoarController.php
<?php
namespace Drupal\dino_roar\Controller;
//use Drupal\dino_roar\DinoServices\HelloGenerator;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class RoarController extends Controller
{
public function roar($count){
//$helloGenerator = new HelloGenerator();
$helloGenerator = $this->get('dino_roar.hello_generator');
$hello = $helloGenerator->getHello($count);
return new Response($hello);
//return new Response("Hello World ".$count);
}
}
dino_roar.info.yml
name: Dino ROAR
type: module
description: "ROAR at you"
package: Custom
core: 8.x
dino_roar.routing.yml
dino_says:
path: /dino/says/{count}
defaults:
_controller: '\Drupal\dino_roar\Controller\RoarController::roar'
requirements:
_permission: 'access content'
dino_roar.services.yml
services:
dino_roar.hello_generator:
class: Drupal\dino_roar\DinoServices\HelloGenerator
The fatal error points to this line of code in the RoarController.php file: $helloGenerator = new HelloGenerator();
This is the Symfony version. I can't find it say 1,2, or 3 in this window.
First of all, your RoarController class needs to extends the Controller class
class RoarController
to
use Symfony\Bundle\FrameworkBundle\Controller\Controller
class RoarController extends Controller
EDIT
Ok now change
public function roar($count){
$helloGenerator = new HelloGenerator();
$hello = $helloGenerator->getHello($count);
return new Response($hello);
//return new Response("Hello World ".$count);
}
to
public function roar($count){
$helloGenerator = $this->get('dino_roar.hello_generator');
$hello = $helloGenerator->getHello($count);
return new Response($hello);
//return new Response("Hello World ".$count);
}
You didn't understand how use services that why I invite you to read this http://symfony.com/doc/current/book/service_container.html#creating-configuring-services-in-the-container
I am trying to setup a Symfony implementation of this PHP library for Chargify https://github.com/johannez/chargify
I'm getting a bit lost working out the best / proper way to set it all up.
I think I need to setup Guzzle as a service, then create a Chargify factory and have that added as a service.
My problem is that in the factory class, when I try and use the Guzzle service I get a fatal error
Fatal error: Using $this when not in object context in /symfony/src/Acme/ChargifyBundle/Factory/ChargifyFactory.php on line 8
This is my Factory class
<?php
namespace Acme\ChargifyBundle\Factory;
class ChargifyFactory implements ChargifyFactoryInterface
{
public static function build($type)
{
$client = $this->get('chargify.guzzle.client');
$className = 'Chargify\\Controller\\' . ucfirst($type);
if (class_exists($className)) {
return new $className($client);
}
else {
throw new Exception("Invalid controller type given.");
}
}
}
If it's useful to see some config, this is my services.yml for the bundle
services:
chargify.guzzle.client.curl_auth:
class: %guzzle.plugin.curl_auth.class%
arguments:
api_key: %chargify_api_key%
chargify.guzzle.client:
class: %guzzle.client.class%
tags:
- { name: guzzle.client }
calls:
- [setBaseUrl, [%chargify_domain%]]
- [addSubscriber, [#chargify.guzzle.client.curl_auth]]
argument: %chargify_domain%
chargify.factory:
class: Acme\ChargifyBundle\Factory\ChargifyFactory
arguments:
- ["type"]
chargify.customer:
class: Acme\ChargifyBundle\Controller\CustomerController
factory_class: Acme\ChargifyBundle\Factory\ChargifyFactory
factory_method: build
arguments:
type: "customer"
How can I use the guzzle client in the Factory with out using
$client = $this->get('chargify.guzzle.client');
EDIT:
I have changed the code as per #alex's answer, but I'm still getting an error. I think this is because the function is static. I've looked though the documents, but I can't see where I can setup a factory without a static function, and when I get rid of static I get a different error.
Runtime Notice: Non-static method Acme\ChargifyBundle\Factory\ChargifyFactory::build() should not be called statically, assuming $this from incompatible context
That is being thrown from some generated code
protected function getChargify_CustomerService()
{
return $this->services['chargify.customer'] = \Acme\ChargifyBundle\Factory\ChargifyFactory::build('customer');
}