Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>Can I not make one PDO object and have that defined in all of my scripts? As well as a UserMapper object?</p> </blockquote> <h3>You're actually looking for a Front Controller.</h3> <p>That is, in order to avoid the same instantiation of the same classes, you should have prepared them. Most people usually do this in <code>bootstrap.php</code>, that "tweaks" all required dependencies.</p> <p>But a front controller implementation also includes a dispatcher and a router. I won't go deep into this, but focus on the problem you're trying to solve instead.</p> <h3>Factory pattern</h3> <p>It basically abstracts instantiation logic. The benefits are: 1) you can delay object instantiation 2) You avoid global state, which is bad for unit-testing. The simplified version of it would look like as:</p> <pre><code>class UserFactory { private $pdo; private $cache = array(); public function __construct($pdo) { $this-&gt;pdo = $pdo; } public function build($mapper) { if (isset($this-&gt;cache[$mapper])) { return $this-&gt;cache[$mapper]; } else { // Inject an instance into a mapper $instance = new $mapper($this-&gt;pdo); // Save the state into a cache $this-&gt;cache[get_class($instance)] = $instance; return $instance; } } } </code></pre> <h3>And finally</h3> <p>A very simplified version of bootstrap-er would look like as,</p> <pre><code>&lt;?php /* File : bootstrap.php */ $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT =&gt; true)); // Include here UserFactory class $userFactory = new UserFactory($dbh); // Its kinda ready to be used </code></pre> <p>You would simply include in all scripts that need to access Users</p> <pre><code>&lt;?php /* File: main.php */ include(__DIR__ . '/bootstrap.php'); $getUser = $userFactory-&gt;build('UserMapper'); $user = $getUser-&gt;findByUserId(41); echo $user-&gt;getEmail(); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload