Check if Symfony Profiler is enabled in own bundle - php

I implemented a own data collector and service decorators to add profiling information about my bundle to the Symfony Profiler.
Now I want them to only be enabled if symfony has the profiler enabled.
I already put all debug service definitions in its own service.yaml to only load it in my bundle extension if a specific condition is met.
$yamlLoader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$yamlLoader->load('services.yaml');
if(<condition>) {
$yamlLoader->load('debug_services.yaml');
}
Is this the correct way to implement this and if yes, which is the safest to match againt to check if the profiler is available and enabled?

You can use SERVER
$yamlLoader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$yamlLoader->load('services.yaml');
if($_SERVER['APP_ENV'] === 'dev' || (bool) $_SERVER['APP_DEBUG']) {
$yamlLoader->load('debug_services.yaml');
}

Related

Can Monolog be used on GAE and have the logging levels recorded in Stack Driver?

There are a number of posts on the internet that indicate the right way to use Monolog on the google app engine (GAE standard) is like so:
$logger = new Monolog\Logger($name);
$syslogHandler = new \Monolog\Handler\SyslogHandler("Ident_String", LOG_USER, \Monolog\Logger::INFO);
$syslogHandler->setFormatter(new \Monolog\Formatter\JsonFormatter());
$logger->pushHandler($syslogHandler);
break;
$logger->warn("Starting priam import." );
That does get me logging, but the level is buried in the textPayload:
textPayload: "[28-Feb-2020 11:00:07] WARNING: [pool app] child 22
said into stderr: "[2020-02-28 06:00:07] match_old.INFO: Doing a super
huge SELECT to get all intls. [] []""
and the level icon is always a stippled out asterisk.
Has something changed? I'm using the php 7.3 run-time on GAE standard. Is there a way to use Monolog on GAE that let's you take proper use of stack driver?
There is a package available that allows you to push Monolog to Stackdriver.
As per the doc:
The supplied StackdriverHandler copies the given log level into the
Stackdriver's severity based on your log method.
It also respects the context argument which allows you to send extra
contextual data with your log message. This will be stored in the log
message under jsonPayload.data.
The source code can be found here monolog-stackdriver
I wound up conditionally loading a different logger locally than I do on GAE. It's workable, but it seems like an unnecessary hack considering monolog is such a popular library. And, oh, it's 2020.
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Google\Cloud\Logging\LoggingClient;
function get_logger($name) {
$kind = getenv('LOG_TYPE')?:'remote';
return _get_logger($kind, $name);
}
function _get_logger($kind, $name) {
if ($kind ==='local') {
$logger = new Monolog\Logger($name);
$logger->pushHandler(new Monolog\Handler\StreamHandler('php://stdout', Monolog\Logger::INFO));
return $logger;
}
$logging = new LoggingClient();
$logger = $logging->psrLogger($name);
return $logger;
}
I'm hoping someone can make this work with monolog.

Creating a Plugin System with Phalcon

I have been looking into how to create a plugin system with Phalcon. I have checked INVO tutorial, Events Management to be more specific. It doesn't look like this is what I exactly need.
In this example it is loading the plugins manually and before establishing database connection.
I need to be able to access the database to check if the plugin actually installed and activated. So I can retrieve settings of installed & activated plugins as well as dynamically add them to the app.
I need to be able to attach the plugins pretty much anywhere; controllers (before / after / within method execution), models (before, after, within method execution) etc.
Does Phalcon provide such feature or do I have to ahead and try to create my own logic without using any framework feature?
Do you have any examples of what you would have plugins do? Or specifics about where Events Management is lacking?
I think you should be able able to get a very flexible system using dependency injection and events management.
It appears you can use the phalcon models before running the application, as long as you place the code after setting the db in the injector.
$plugins = \Plugin::find([
'active = :active:',
'bind'=>[
'active'=>1
]
]);
foreach($plugins as $plugin){
if(file_exists($plugin->filename)){
include $plugin->filename;
}
}
and in the file you could have code to subscribe to events, and/or add new dependencies.
// plugin file - for a db logger
$eventsManager = new \Phalcon\Events\Manager();
$logger = new \PhalconX\Logger\Adapter\Basic();
$profiler = $phalconDi->getProfiler();
$eventsManager->attach('db', function($event, $phalconConnection) use ($logger, $profiler) {
if ($event->getType() == 'beforeQuery') {
$profiler->startProfile($phalconConnection->getSQLStatement());
$logger->log($phalconConnection->getSQLStatement(), \Phalcon\Logger::INFO, $phalconConnection->getSQLVariables());
}
if ($event->getType() == 'afterQuery') {
$profiler->stopProfile();
}
});
or
class myHelper{ ... }
$phalconDi->set('myHelper', function() use ($phalconConfig, $phalconDi) {
$helper = new myHelper();
$helper->setDi( $phalconDi );
return $helper;
});

Using MongoDb in the PHP Phalcon framework

I am currently experimenting with the Phalcon Framework, and running into some complications when I attempt to save content into the Mongo Database. I can correctly setup the MySQL database without issues. Whenever I send the simple request through I get a 500 Internal server error (checking devTools). I have setup everything accordingly as the documentation specifies.
This is my simple index.php bootstrap Mongo initialisation along with the collection manager:
// Setting Mongo Connection
$di->set('mongo', function() {
$mongo = new Mongo();
return $mongo->selectDb("phalcon");
}, true);
// Setting up the collection Manager
$di->set('collectionManager', function(){
return new Phalcon\Mvc\Collection\Manager();
}, true);
This is my controller handling the request:
public function createAction() {
$user = new User();
$user->firstname = "Test ACC";
$user->lastname = "tester";
$user->password = "password";
$user->email = "testing#example.com";
if($user->create() == false) {
echo 'Failed to insert into the database' . "\n";
foreach($user->getMessages as $message) {
echo $message . "\n";
}
} else {
echo 'Happy Days, it worked';
}
}
And finally my simple User class:
class User extends \Phalcon\Mvc\Collection {
public $firstname;
public $lastname;
public $email;
public $password;
public $created_at = date('Y-m-d H:i:s');
}
Much appreciated for everyones input/suggestions.
i think it's because your installation of Mongo is not valid.
try printing phpinfo() and check if mongo is loaded at all, if not - install it, add to ini files (if you use cli, don't forget to add to cli ini too) and reach the moment, when mongo is fully loaded.
try mongo w/o phalcon. any simple connection/insertation. you can see here: Fatal Error - 'Mongo' class not found that there are problems with apache module version for some people. Try reinstalling different mongo version.
if you can print this out:
echo Phalcon\Version::get();
there should be no problems with phalcon instalation
to validate mongo installation, try any of examples from php.net:
http://www.php.net/manual/en/mongo.tutorial.php
A little bit late, but for anyone else facing this issue, it would be a good idea to try and connect to mongo (run "mongo" in your terminal) to ensure that mongo is setup correctly in your dev environment.
Also, I usually find in this sort of situation, that adding a collection to a database in mongo and then testing the CRUD process with a simple read helps move things along. If all is well at this stage, then you know your app is able to connect and you can proceed to writes, and so on.
This looks useful.

Using simplesamlphp 1.10 with cakePHP 2.3 not working

I'm trying to implement the SimpleSAMLphp authentication tool in cakePHP.
I wrote a SamlAuthenticate component in app\Controller\Component\Auth which looks like this:
class SamlAuthenticate extends Component {
[...]
public function authenticate(CakeRequest $request, CakeResponse $response) {
$source = null;
$as = null;
if ($this->Session->check('Saml.source')) {
$source = $this->Session->read('Saml.source');
}
if ($source) {
require_once($this->settings['path'] . DS . 'lib' . DS . '_autoload.php');
$as = new SimpleSAML_Auth_Simple($source);
if(!$as->isAuthenticated()) {
$as->login();
} else {
return $as->getAttributes();
}
}
return false;
}
}
But I'm always getting an loop between the identity provider and my cake application.
I was wondering, if my server is the problem or I did something wrong with the configuration of the identity provider, so I wrote a simple test script and it worked without a problem:
require_once('/../simplesamlphp/lib/_autoload.php');
$as = new SimpleSAML_Auth_Simple('facebook');
$as->requireAuth();
echo $as->isAuthenticated();
So, something in cakePHP breaks the authentication process. The SimpleSAMLAuthToken is set correctly (I can see that through the SimpleSAMLphp admin panel), but $as->isAuthenticated() always returns false.
I also tried https://github.com/bvidulich/CakePHP-simpleSAMLphp-Plugin with the same result.
maybe you are in a session conflict.
Take a look on the LostState info of the simpleSAMLphp documentation.
A fast workaround to see if that is your problem:
Configure the simplesamlphp to save the session on memcache. You will need to install a memcache server, the memcache php driver (remember to restart your apache after install ir) and then edit the config/config.php file of simpleSAMLphp and set
'store.type' => 'memcache',
Check that the simpleSAMLphp can write a session using the cookie extension of firefox. (Take a look on the session/cookie params of the config/config.php file.

Doctrine for PHP configuration

Hi, everyone!
I'm building a PHP site and I decided to go with Doctrine as DBAL and ORM. I'm a bit rusty on my PHP skills, so please help me understand one thing.
The way to configure Doctrine, as specified in their docs is to execute code like this:
if ($applicationMode == "development") {
$cache = new \Doctrine\Common\Cache\ArrayCache;
} else {
$cache = new \Doctrine\Common\Cache\ApcCache;
}
$config = new Configuration;
$config->setMetadataCacheImpl($cache);
$driverImpl = $config->newDefaultAnnotationDriver('/path/to/lib/MyProject/Entities');
$config->setMetadataDriverImpl($driverImpl);
$config->setQueryCacheImpl($cache);
$config->setProxyDir('/path/to/myproject/lib/MyProject/Proxies');
$config->setProxyNamespace('MyProject\Proxies');
if ($applicationMode == "development") {
$config->setAutoGenerateProxyClasses(true);
} else {
$config->setAutoGenerateProxyClasses(false);
}
$connectionOptions = array(
'driver' => 'pdo_sqlite',
'path' => 'database.sqlite'
);
What I'm puzzled about is how should you execute this code. Is it something you put in a config.php file and include in each of your pages, basically executing this each time a page is processed? Or am I supposed to do this configuration once?
On a related note - please help me understand how setting cache to ArrayCache instead of APC cache helps me during development?
Thanks!
doctrine is a pretty hard choice if your PHP skills are rusty... Anyway...
You can create the connection and eventmanger once in a bootstrap file. Then you can pass the eventmanager instance to your class constructors or make it availably through a static registry (dirty dirty dirty) or ...
This is a good starting point (for orm 2.0):
http://www.doctrine-project.org/docs/orm/2.0/en/tutorials/getting-started-xml-edition.html
The only reason for using ArrayCache in dev mode I can think of is, that you do not have to configure APC at that point and can focus on your coding. In production mode APC gives you the extra boost and is highly recommended.
Regards
Flo

Categories