zend_db standalone - zend-db

i want to use zend_db standalone cos zend framework is too much for my project but i'm new with it,
is it correct to do this:
$pdoParams = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES
UTF8;');
$params = array(
'host' => 'localhost',
'username' => 'ss_fraat',
'password' => 'jos10',
'dbname' => '_a2hDB',
'driver_options' => $pdoParams
);
try {
$db = Zend_Db::factory('PDO_MYSQL', $params);
//set default adapter
Zend_Db_Table_Abstract::setDefaultAdapter($db);
} catch (Exception $e) {
exit($e->getMessage());
}
//save Db in registry for later use
Zend_Registry::set('dbAdapter', $db);
then in any class do this:
$db = Zend_Registry::get('db');
/** quote to avoid sql injection */
$date = $db->quote('1980-01-01');
$sql = 'SELECT * FROM product WHERE name = ' . $date;
$result = $db->query($sql);
$db->query(); //run a query
i really need to do this
Zend_Db_Table_Abstract::setDefaultAdapter($db);
i get this code from a website,
is it necessary to use Zend_Db_Table_Abstract if i'm not using the full zend framework,
or it is better for example to use this:
$db = Zend_Db::factory( ...options... );
$select = new Zend_Db_Select($db);
what i want is to setup a pdo/mysql connexion in my bootstrap php page and be able to get that db instance in any class without starting a new connexion to execute queries but i'm not sure how to do that use Zend_Db_Table_Abstract or Zend_Db_Select use the registry Zend_Registry::set('dbAdapter', $db) or not
thanks a lot

The purpose of Zend_Db_Table_Abstract is so you can create your own model classes based around the Table Data Gateway design pattern. The idea of that pattern is that you have a class that encapsulates all the sql you would need for interfacing with a table. So the assumption is that you will be creating model classes that extend Zend_Db_Table_Abstract for each table. If you are going to do that, then you will want to call Zend_Db_Table_Abstract::setDefaultAdapter($db) in your setup/bootstrap. Recent versions of ZF provide as an alternative a quick way of getting basic functionality without having to create a custom class definition by just instantiating Zend_Db_Table:
$userTable = new Zend_Db_Table('users');
In summary, none of this particularly has to do with the MVC part of the framework, although some people choose to use Zend_db as the basis for db connections and models, instead of using a more fully featured ORM like Doctrine or Propel.
The other code you provided simply illustrates that you do not need to use Zend_Db_Table_Abstract either -- you can simply setup an instance of a Zend_Db_Adapter and use that instance to call query() or its other methods.

Related

How to use existing data from the database in Codeception FactoryMuffin?

I'm trying to set up easy test data in my Acceptance tests:
public function shouldUseAFakeAccountHolder(AcceptanceTester $I) {
$I->have(AccountHolder::class);
// ...
}
I've copied the example code from the Codeception documentation and modified it with my entity names (as well as fixing the bugs).
<?php
public function _beforeSuite()
{
$factory = $this->getModule('DataFactory');
// let us get EntityManager from Doctrine
$em = $this->getModule('Doctrine2')->_getEntityManager();
$factory->_define(AccountHolder::class, [
'firstName' => Faker::firstName(),
// Comment out one of the below 'accountRole' lines before running:
// get existing data from the database
'accountRole' => $em->getRepository(AccountRole::class)->find(1),
// create a new row in the database
'accountRole' => 'entity|' . AccountRole::class,
]);
}
The relationship using existing data 'accountRole' => $em->getRepository(AccountRole::class)->find(1) always fails:
[Doctrine\ORM\ORMInvalidArgumentException] A new entity was found through the relationship 'HMRX\CoreBundle\Entity\AccountHolder#accountRole' that was not configured to cascade persist operations for entity: HMRX\CoreBundle\Entity\AccountRole#0000000062481e3f000000009cd58cbd. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example #ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'HMRX\CoreBundle\Entity\AccountRole#__toString()' to get a clue.
If I tell it to create a new entry in the related table 'accountRole' => 'entity|' . AccountRole::class, it works, but then it adds rows to the table when it should be using an existing row. All the role types are known beforehand, and a new random role type makes no sense because there's nothing in the code it could match to. Creating a duplicate role works, but again it makes so sense to have a separate role type for each user since roles should be shared by users.
I've had this error before in Unit tests, not Acceptance tests, when not using Faker / FactoryMuffin, and it's been to do with accessing each entity of the relationship with a different instance of EntityManager. As soon as I got both parts using the same instance, it worked. I don't see how to override the native behaviour here though.
It works (at least in Codeception 4.x) by using a callback for the existing relation:
<?php
public function _beforeSuite()
{
$factory = $this->getModule('DataFactory');
$em = $this->getModule('Doctrine2')->_getEntityManager();
$factory->_define(AccountHolder::class, [
'firstName' => Faker::firstName(),
'accountRole' => function($entity) use ($em) {
$em->getReference(AccountRole::class)->find(1);
},
]);
}
I've found it here: https://github.com/Codeception/Codeception/issues/5134#issuecomment-417453633

How in codeception to make rollback a database if the test failed?

I need to test the feature in account. But for this need register an account. If the feature does not work correctly and the test fails, how do I can automatically delete an account from a database (account created during testing)?
I think you have a few options.
You can do clean-up in your Cest class's _before or _after methods (if you use a framework you could use an ORM to delete all accounts for example).
Codeception's Db module (see https://codeception.com/docs/modules/Db) also has a cleanup flag which, when true, will load a user-defined database dump before each test (you could create a dump with no accounts).
There might be other options too. If you use Yii2 for example, the Yii2 module for Codeception has a cleanup flag that will wrap tests in a transaction if true (see https://codeception.com/for/yii).
We are facing problems like this, too. If you insert the account with the DB module of codception you can use the cleanup flag and it will automaticly clean up the database after each run.
If you create the account by a test and you want to go sure that the account isn't existing before you start the test you can extend the DB module by a delete function (that has to used with care, we only allow that in testing environments).
<?php
namespace Helper\Shared;
class DbHelper extends \Codeception\Module {
public function deleteFromDatabase($table, $criteria)
{
$dbh = $this->getModule('Db')->_getDbh();
$query = "delete from `%s` where %s";
$params = [];
foreach ($criteria as $x => $y) {
$params[] = "`$x` = '$y'";
}
$params = implode(' AND ', $params);
$query = sprintf($query, $table, $params);
codecept_debug($query);
$this->debugSection('Query', $query, json_encode($criteria));
$sth = $dbh->prepare($query);
return $sth->execute(array_values($criteria));
}
}
This can be used in the test code with ...
$I->deleteFromDatabase('account', ['id' => '123456']);
If it's possible the DB Module should be used to create the account and clean it up again. This method above is pretty dangerous dependend on the systems you are using it.

vanilla php ldap query works. Symfony 3 ldap query fails. Why?

I'm trying to figure out how to use the Ldap class in Symfony3. I've successfully created and bound a connection but I can't get any results on a query. To make sure that the query actually works, I ran a bare php version:
if($lconn = ldap_connect('ds.mydomain.ca')){
ldap_set_option($lconn, LDAP_OPT_REFERRALS, 0);
ldap_set_option($lconn, LDAP_OPT_PROTOCOL_VERSION, 3);
if($lbind = ldap_bind($lconn,'webuser','password')){
$filter ="(&(sn=Smith)(givenname=J*))";
if(!$result = ldap_search($lconn, "dc=ds, dc=mydomain, dc=ca", $filter)) throw \Exception("Error in search query: ".ldap_error($lconn));
$output = ldap_get_entries($lconn, $result);
}else{
$output='bind failed';
}
} else {
$output= 'connection failed';
}
It returns the expected number of results.
On the other hand, this query done with Symfony 3's Ldap component returns 0 results:
//use Symfony\Component\Ldap\Ldap
$ldap = Ldap::create('ext_ldap', array(
'host' => 'ds.mydomain.ca',
'version' => 3,
'debug' => true,
'referrals' => false,
));
$ldap->bind('webuser', 'password');
$q = $ldap->query("dc=ds, dc=nrc, dc=ca", "(&(sn=Smith)(givenname=J*))");
$output = $q->execute();
Any idea why the Symfony ldap query fails when all its options should be identical to those I used for the bare php query?
I reposted this question on the Symfony github. #ChadSikorra was there too. And he made it clear what my issue was. Here's his explanation:
If you look at the collection class, nothing is done with the result
resource until initialize() is called in the class. If you do
return array('output' => array('bare' => $bare, 'symfony' =>
$symf->toArray())); it will call initialize and you'll see the
entries populated in the class. Unless there's something else going
on.
Do you still experience this issue with the latest 3.1+ versions?
Sorry but I don't go very often on Stack Overflow and spend most of my time on Github so I didn't see your question before.
As #ChadSikorra said, you should be using the toArray() method of the resulting Collection class, or you should iterate on the results directly.
The implementation is made so that the results are traversed in a memory-efficient manner, without storing all the results in an array by default, but the toArray() method can do this for you. Behind the scenes,it actually converts the resulting itératif to an array using the appropriate PHP function (iterator_to_array).
By the way, there used to be some inconsistency between the iterator and the toArray() function call, but that has been fixed in recent versions.
Cheers!

How to set Attribute to PDO connection in Codeigniter

How to set attributes (PDO::ATTR_ERRMODE) on the PDO database handle in Codeigniter?
I think a better option is to use a MY_Model (which you then extend and this is available then across the application) and define something like this in the construct:
$this->db->conn_id->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
Note conn_id allows you to access the main PDO object.
There are two ways:
1. The lazy (hacky) way
Add to the following code into system/core/database/drivers/pdo/pdo_driver.php (in CI 3):
public function db_connect($persistent = FALSE)
{
$this->options[PDO::ATTR_PERSISTENT] = $persistent;
// Added code start
$this->options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
// Added code end
try
{
return new PDO($this->dsn, $this->username, $this->password, $this->options);
...
}
2. The right way
Extend Database Driver and add the same line
Note: If you will set PDO::ERRMODE_EXCEPTION in Codeigniter it will show exception errors even in Production environment.

CakePHP: get user info in models

I'm moving some of my find code inside models.
Previously in my controller I had
$this->Book->Review->find('first', array(
'conditions' => array(
'Review.book_id' => $id,
'Review.user_id' => $this->Auth->user('id')
)
));
so in my Review model I put something like
function own($id) {
$this->contain();
$review = $this->find('first', array(
'conditions' => array(
'Review.book_id' => $id,
'Review.user_id' => AuthComponent::user('id')
)
));
return $review;
}
So I'm calling AuthComponent statically from the Model. I know I can do this for the method AuthComponent::password(), which is useful for validation. But I'm getting errors using the method AuthComponent::user(), in particular
Fatal error: Call to a member function
check() on a non-object in
/var/www/MathOnline/cake/libs/controller/components/auth.php
on line 663
Is there a way to get the info about the currently logged user from a model?
Create a new function in the "app_model.php" ("AppModel.php" in CakePHP 2.x), so it will be available at all models within our application:
function getCurrentUser() {
// for CakePHP 1.x:
App::import('Component','Session');
$Session = new SessionComponent();
// for CakePHP 2.x:
App::uses('CakeSession', 'Model/Datasource');
$Session = new CakeSession();
$user = $Session->read('Auth.User');
return $user;
}
in the model:
$user = $this->getCurrentUser();
$user_id = $user['id'];
$username = $user['username'];
The way that I use is this:
App::import('component', 'CakeSession');
$thisUserID = CakeSession::read('Auth.User.id');
It seems to work quite nicely :-)
I think the code is fine as it is and belongs in the Controller, or at the very least it needs to receive the ids from the Controller and not try to get them itself. The Model should only be concerned with fetching data from a data store and returning it. It must not be concerned with how the data is handled in the rest of the application or where the parameters to its request are coming from. Otherwise you paint yourself into a corner where the ReviewModel can only retrieve data for logged in users, which might not always be what you want.
As such, I'd use a function signature like this:
function findByBookAndUserId($book_id, $user_id) {
…
}
$this->Review->findByBookAndUserId($id, $this->Auth->user('id'));
There is a nice solution by Matt Curry. You store the data of the current logged user in the app_controller using the beforeFilter callback and access it later using static calls. A description can be found here:
http://www.pseudocoder.com/archives/2008/10/06/accessing-user-sessions-from-models-or-anywhere-in-cakephp-revealed/
EDIT: the above link is outdated: https://github.com/mcurry/cakephp_static_user
I think this is not good idea to get value from Session. Better solution to get logged user id inside any model simply try this:
AuthComponent::user('id');
This will work almost every where. View, Model and Controller
Dirtiest way would be to just access the user information in the Session. Least amount of overhead associated with that.
The "proper" way would probably be to instantiate the AuthComponent object, so that it does all the stuff it needs to be fully operational. Much like a death star, the AuthComponent doesn't really work well when not fully setup.
To get a new AC object, in the model:
App::import( 'Component', 'Auth' );
$this->Auth = new AuthComponent();
Now you can use $this->Auth in the model, same as you would in the controller.
For CakePHP 3.x this easy component is available: http://cakemanager.org/docs/utils/1.0/components/globalauth/. Direct accessing the Session is not possible because of different SessionKeys.
With the GlobalAuthComponent you can access your user-data everywhere with: Configure::read('GlobalAuth');.
Greetz
Bob
I use cake 2.2 and these both work great:
$this->Session->read('Auth.User');
//or
$this->Auth->user();
You can also get a field of currently logged in user:
$this->Session->read('Auth.User.email');
//or
$this->Auth->user()['email'];
None of these solutions work in CakePHP version 3. Anyone know of a way to do this? Right now, I'm completely stepping around the framework by accessing the $_SESSION variable directly from my model.