note 106125 added to class.pdo

From: Date: Wed, 12 Oct 2011 20:10:27 +0000
Subject: note 106125 added to class.pdo
Groups: php.notes 
Request: Send a blank email to php-notes+get-183833@lists.php.net to get a copy of this message
PDO and Dependency Injection Dependency injection is good for testing. But for anyone wanting various data mapper objects to have a database connection, dependency injection can make other model code very messy because database objects have to be instantiated all over the place and given to the data mapper objects. The code below is a good way to maintain dependency injection while keeping clean and minimal model code. <?php class DataMapper { public static $db; public static function init($db) { self::$db = $db; } } class VendorMapper extends DataMapper { public static function add($vendor) { $st = self::$db->prepare( "insert into vendors set first_name = :first_name, last_name = :last_name" ); $st->execute(array( ':first_name' => $vendor->first_name, ':last_name' => $vendor->last_name )); } } // In your bootstrap $db = new PDO(...); DataMapper::init($db); // In your model logic $vendor = new Vendor('John', 'Doe'); VendorMapper::add($vendor); ?> ---- Server IP: 64.71.164.2 Probable Submitter: 130.160.166.106 ---- Manual Page -- http://www.php.net/manual/en/class.pdo.php Edit -- https://master.php.net/note/edit/106125 Del: integrated -- https://master.php.net/note/delete/106125/integrated Del: useless -- https://master.php.net/note/delete/106125/useless Del: bad code -- https://master.php.net/note/delete/106125/bad+code Del: spam -- https://master.php.net/note/delete/106125/spam Del: non-english -- https://master.php.net/note/delete/106125/non-english Del: in docs -- https://master.php.net/note/delete/106125/in+docs Del: other reasons-- https://master.php.net/note/delete/106125 Reject -- https://master.php.net/note/reject/106125 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#183833) next »