Created
April 5, 2013 16:30
-
-
Save phalcon/5320671 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $eventsManager = new \Phalcon\Events\Manager(); | |
| $di = new \Phalcon\DI(); | |
| $connection = new \Phalcon\Db\Adapter\Pdo\Sqlite([ | |
| "dbname" => "sample.db" | |
| ]); | |
| $connection->setEventsManager($eventsManager); | |
| $eventsManager->attach('db', | |
| function ($event, $connection) { | |
| switch ($event->getType()) { | |
| case 'beforeQuery': | |
| echo $connection->getSqlStatement(), '<br>'; | |
| break; | |
| case 'beginTransaction': | |
| echo 'BEGIN', '<br>'; | |
| break; | |
| case 'commitTransaction': | |
| echo 'COMMIT', '<br>'; | |
| break; | |
| case 'rollbackTransaction': | |
| echo 'ROLLBACK', '<br>'; | |
| break; | |
| } | |
| } | |
| ); | |
| $di['db'] = $connection; | |
| $di['modelsManager'] = new \Phalcon\Mvc\Model\Manager(); | |
| $di['modelsMetadata'] = new \Phalcon\Mvc\Model\Metadata\Memory(); | |
| $di['response'] = new \Phalcon\Http\Response(); | |
| //$connection->execute('CREATE TABLE artist (id integer primary key, name varchar(120) not null, photo_id int not null)'); | |
| //$connection->execute("INSERT INTO artist VALUES (null, 'Björk', 1)"); | |
| /** | |
| * Represents artist | |
| */ | |
| class Artist extends Phalcon\Mvc\Model | |
| { | |
| public $id; | |
| public $name; | |
| public $photo_id; | |
| public function initialize() | |
| { | |
| // Related tracks | |
| $this->hasMany('id', 'Artist\Track', 'artist_id', [ | |
| 'alias' => 'Tracks' | |
| ]); | |
| } | |
| public function getSource() | |
| { | |
| return 'artist'; | |
| } | |
| } | |
| class Application implements Phalcon\DI\InjectionAwareInterface | |
| { | |
| protected $di; | |
| public function getDI() | |
| { | |
| return $this->di; | |
| } | |
| public function setDI($di) | |
| { | |
| $this->di = $di; | |
| } | |
| public function handle() | |
| { | |
| $di = $this->getDI(); | |
| $db = $di['db']; | |
| try { | |
| $db->begin(); | |
| $artist = new \Artist(); | |
| $artist->name = 'Hello'; | |
| if (!$artist->save()) { | |
| throw new \Exception('Row was not saved'); | |
| } | |
| throw new \Exception("Test exception"); | |
| echo 'fuck, no effect'; // never is shown | |
| $db->commit(); | |
| $content = 'committed!'; | |
| } catch (\Exception $e) { | |
| $db->rollback(); | |
| $content = $e->getMessage(); | |
| } | |
| $response = $di['response']; | |
| $response->setContent($content); | |
| return $response; | |
| } | |
| } | |
| $app = new Application(); | |
| $app->setDI($di); | |
| echo $app->handle()->getContent(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment