doctrine dbal count number of querys executed - php

I have build my own mvc framework and i'm using Doctrine DBAL 2.3 as database layer.
At the moment i'm working on a profiler for this framework.
One of the things i want to put in the profiler is the number of querys that were executed on the current page.
My question is: can i get the number of querys from Doctrine?
Yes? How can i do this?
No? Is there a way to build something custom that works with Doctrine and does the trick?
I hope there is someone that can answer my question, thank you.

Doctrine 2 provides a simple interface for logging, namely \Doctrine\DBAL\Logging\SQLLogger()
https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Logging/SQLLogger.php
$config = new Doctrine\ORM\Configuration ();
// ... config stuff
$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
$connectionParams = array(
'dbname' => 'example',
'user' => 'example',
'password' => 'example',
'host' => 'localhost',
'driver' => 'pdo_mysql');
//make the connection through an Array of params ($connectionParams)
$em = EntityManager::create($connectionParams, $config);

Related

PDO Class Handler

I often make small projects for friends or for people on forum I visit.
For instance, it's create a user space, or chat page, or stuff like that.
That's why I think Frameworks/ORM is not suitable for the size of these projects, the code is often less than 300 lines.
But in all cases, I use PDO, and it's really using to write the SQL string, check the docs to make a INSERT, .. So I was thinking of extending the PDO Class with a chaining approach, like this:
$pdo->create('users', array(
'id' => 'int',
'username' => 'text',
'password' => 'text'
));
$pdo->insert(array(
'username' => $user,
'password' => md5($password)
))->in('users');
$pdo->update(array(
'username' => $new_user
))->in('users')->where('id', $user_id);
$pdo->select()->from('users')->where('id', $user_id)->row();
$pdo->select('username')->from('users')->rows();
$pdo->drop('users');
$pdo->close();
And if PDO or the way of storing (mysql/sqlite/...) changes, I just have to edit the class and it's done.
So, does a similar class exist ?
And is it a good idea to make things like this ?
EDIT: I'm sorry to bump this thread, but I'm afraid that no-one has made a thing like this..
You are contradicting yourself... You are talking about writing a QueryBuilder and/or DBAL on top of PDO (which is a pretty complex thing to do in terms of the amount of code needed to support multiple DB vendors) Yet you shy away from a framework. Doesn't make much sense.
That said there are DBAL and QueryBuilders out there that can be used outside of a greater framework. Personally I'd say go with Doctrine DBAL. An example of using its QueryBuilder:
$conn = DriverManager::getConnection($connectionInfo);
$queryBuilder = $conn->createQueryBuilder();
$queryBuilder
->select('*')
->from('users')
->where('id = ?')
->setParameter(0, $user_id);
As for a framework there are also "micro frameworks" which serve as a simple MVC stack (when compared to something like Laravel, Cake, Symfony2, etc.). For projects of the nature you are talking I would in fact probably use Silex in combination with Doctrine DBAL.

How do I access object data that came from a model?

I'm looking at porting over some functions from the CakePHP 2.0 Users plugin into CakePHP 3.0. I've encountered this line in the old code:
$user = $this->{$this->modelClass}->passwordReset($this->request->data);
I debugged $user here and got a huge object filled with all kinds of data that I need. Perfect:
'properties' => [
'password' => '*****',
'id' => '53f7b636-e558-4eef-9064-1e78494ef653',
'username' => 'blahblah',
...
]
I thought everything was working perfectly until the next line:
$Email->to($user[$this->modelClass]['email'])
This is the first line of an email about to send. Here, $user[$this->modelClass]['email'] returns null. So I tried accessing the object directly, like so:
debug($user['properties']['email'])
This still returns null, I'm assuming because I'm trying to access parameters from a model. I'm not exactly sure what is different in CakePHP 3.0 for $this->modelClass or if I goofed up elsewhere. Any ideas?
I should be $user->email, as the new ORM now returns objects instead of arrays

How to make a Changelog?

For a Web-Application with many Database related events I want to build a Changelog. That should log what users have done, so its a Userlog too.
The App is huge, has a complex role based user access system and there will be hundreds of different events (changes) that may occur.
This all should be Database-Driven, in PHP and needs at least a View to search the Logs.
But in short, I have totally no idea how to design that all and need some tips or inspirations, maybe what others have done.
I've done this in the past and found basically 2 approaches: Model-based and Controller-based.
Model-based within the model itself override the save and update methods (assuming an ActiveRecord pattern) to create a new entry in the ChangeLog table.
Controller-based add the ChangeLog record creation logic to each controller that you want to track.
I prefer the Controller-based approach since you have more control over what's going on and when. Also, you have full access to the user session so it's easier to add tracking for auditing purposes.
Have solved that much more easy as it appears with my first thoughts.
This should do it most times without a comment:
protected function log($comment = ''){
$user = $this->user();
ORM::factory('Changelog')->vaules(array(
'user_id' => $user->pk(),
'section_id' => $user->section->pk(),
'username' => $user->username.'#'.$user->section->name,
'time' => time(),
'uri' => $this->uri($this->request->param(), $this->request->query()),
'controller' => $this->request->controller(),
'action' => $this->request->action(),
'post' => serialize($this->request->post()),
'comment' => $comment,
))->save();
}
A simple $this->log() and all is done.
Result: http://charterix.sourceforge.net/log.jpg

Drupal7 - How to select records from mysql in page?

While i'm creating basic page in drupal i select text format to PHP code. Now I can write PHP code here.
I want to list records from MySQL, How can I include a database-connection here?
Is it good way writing PHP code in content?
you can directly call drupal api functions like db_query() without adding any dbconection in a page. Adding php codes inside a page is not recommented, try to create your own module for that or use views
First: you should not use the PHP-input format. The fact that it is there is highly debated in Drupal, with many people leaning towards removing it entirely. It is both a security nightmare and a maintanance-horror.
That said, the PHP you are looking for is:
<?php
// Create an object of type SelectQuery
$query = db_select('users', 'u');
// Add extra detail to this query object: a condition, fields and a range
$query->condition('u.uid', 0, '<>');
$query->fields('u', array('uid', 'name', 'status', 'created', 'access'));
$query->range(0, 50);
?>
More on dynamic queries is found on Drupal.org. No need to set-up your database, Drupal already handled that.
In case you want your code to connect to a differnt database then the main Drupal-database, you can either add that database to your settings.php:
$databases['gallery']['gallery'] = array(
'driver' => 'mysql',
'database' => 'gallery',
'username' => 'username',
'password' => 'secret',
'host' => 'localhost',
);
This introduces a new database resource called "gallery" using a database "gallery". Useful when you want to use resources from another database, like records from a "gallery application".
You can then query that database using the key in the $options-parameter, like so:
<?php
// Create an object of type SelectQuery
$query = db_select('pictures', 'p', array('target' => 'gallery'));
// Add extra detail to this query object: a condition, fields and a range
$query->condition('p.status', 'published', '=');
$query->fields('p', array('path', 'title', 'date'));
$query->range(0, 50);
?>

Zend Framework 2 - DI and having to inject table adapter into tables... tedious?

I just read the Rob Allen's akrabat ZF2 tutorial (http://akrabat.com/wp-content/uploads/Getting-Started-with-Zend-Framework-2.pdf) on how to inject dependencies into your stuff like, injecting in your table adapter into your table classes.
This seems to be how I'm supposed to do it:
array(
'Application\Model\DbTable\UserTable',
) => array(
'parameters' => array(
'config' => 'Zend\Db\Adapter\PdoMysql',
)
),
array(
'Application\Model\DbTable\UserProfileTable',
) => array(
'parameters' => array(
'config' => 'Zend\Db\Adapter\PdoMysql',
)
),
Ok that's pretty cool but I've got around 84 tables so am I going to have to add each of these and say that I want PdoMySQL injecting into them all. Is there any proper way to do this such as specifying my entire DbTable folder? Not even this works:
array(
'Application\Model\DbTable\UserTable',
'Application\Model\DbTable\UserProfileTable'
) => array(
'parameters' => array(
'config' => 'Zend\Db\Adapter\PdoMysql',
)
),
Anyone else doing this and found a better solution?
Thanks, Dom
Your question is a good one, and I agree, this a scenario where dependency injection does NOT make sense. I haven't browsed the ZF2 API yet, did they completely abandon the ability to bind adapter at the connection level, rather than the table level?
In my database class I use a yaml file to store connection settings; username, password, adapter, etc. I did it in a format which can be passed straight to Zend_Config, which can then be passed to the Zend_Db class.
// Entry in connection.yml
database:
adapter: Pdo_Mysql
params:
host: myhost
dbname: mydatabase
username: myusername
password: mypassword
// Parse yaml file to get above snippet in an array ($dbConnectionparams)
$config = new Zend_Config($dbConnectionParams);
$dbo = Zend_Db::factory($config->database);
Now, If I ever need to change the adapter for a database connection I only need to change it in one location, the connection.yml file.
Also, I believe you can store this type of connection data in various other formats (xml, etc).
You should implement Zend\Db\Adapter\AdapterAwareInterface in your model classes and request them via service manager in your controllers. Take a look at my blog post for more details: http://cmyker.blogspot.com/2012/11/zend-framework-2-model-database-adapter.html

Categories