Skip to content

Instantly share code, notes, and snippets.

@phalcon

phalcon/tx.php

Created Feb 5, 2013
Embed
What would you like to do?
<?php
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
$di = new Phalcon\DI\FactoryDefault();
$eventsManager = $di['eventsManager'];
$eventsManager->attach('db', function($event, $connection){
if ($event->getType() == 'beforeQuery') {
echo $connection->getSqlStatement(), '<br>', PHP_EOL;
}
});
$connection = new Phalcon\Db\Adapter\Pdo\Mysql(array(
'host' => 'localhost',
'username' => 'scott',
'password' => 'tiger',
'dbname' => 'test'
));
$connection->setEventsManager($eventsManager);
//Setup a connection
$di->set('db', $connection);
class Users extends Phalcon\Mvc\Model
{
}
class Toolbars_Install extends Phalcon\Mvc\Model
{
public function getSource()
{
return 'toolbars_install';
}
}
//Doing values insertion
try {
$userId = md5('hello');
$request = new Phalcon\Http\Request();
$transactionManager = new TxManager();
$transaction = $transactionManager->get();
$user = Users::findFirst("uid='".$userId."'");
if ($user == false) {
$user = new Users();
}
$user->setTransaction($transaction);
$user->uid = $userId;
$user->status = 'active';
$user->created = date('Y-m-d H:i:s');
//$ipAddress = explode(',', $request->getClientAddress(true));
$ipAddress = '127.0.0.1';
if ($user->save() == true) {
$toolbar = new Toolbars_Install();
$toolbar->setTransaction($transaction);
$toolbar->ip_address = $ipAddress[0];
$toolbar->created = date('Y-m-d H:i:s');
$toolbar->uid = $user->id; //Is this line ok?
if ($toolbar->save() == true) {
$user->toolbar_install_id = $toolbar->id;
$user->save();
} else {
$errors = $toolbar->getMessages();
$transaction->rollback('Unable to save model [toolbar], error: '.$errors[0]);
}
} else {
$transaction->rollback('Unable to save model [user], error: '.$errors);
}
$transaction->commit();
} catch(TxFailed $e) {
//\Classes\Utils\Log::exception($app->config->logs->toolbars->install, $e);
echo $e->getMessage();
} catch (Exception $e) {
//\Classes\Utils\Log::exception($app->config->logs->toolbars->install, $e);
echo $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment