Instantiating multiple PHP objects from a single PDO array (without boilerplate) -
If you want to get an object from the database, the PDO is very useful:
$ Obj = $ handle-> Obtain all (PDO :: FETCH_CLASS, $ obj_name); If you expect to return more than one square type in a row (such as: when doing JOINS), the PDO is less helpful:
< Code> $ handle-> FetchAll (PDO :: FETCH_ASSOC); Okay - I'm feeling terribly awesome except for every kind of method.
My question is : How can I instantize many objects from a single array in a beautiful, strong way when the content of that array can show everyone, none Some or more than necessary for classes? Example:
Given an array that comes back from the PDO database $ vars = ('a' = & gt; 1, 'b' = & gt; ; 2, 'c' = & gt; 3, 'x' => 7, 'y' = 8, 'z' => 9) , objects ABC < / Code> build ( $ a , $ b and $ c should be required) and without too much copy and pasting XYZ ( $ x , $ y , $ z ). Option 1 Class ABC {Private $ a, $ b, $ c; Function __ conversion ($ a = zero, $ b = zero, $ c = null) {$ this- & gt; $ a = $ a? $ A: $ this- & gt; A; $ This- & gt; $ B = $ b? $ B: $ this- & gt; B; ... (Boilerplate code / copy-and-paste / lots is necessary that the instant code has already created all the variables in the correct order) ABCFactory ($ vars = array ()) {new ABC ($ Wars ['A'], $ wars ['B'] / em> option 2 ] Return ... (Better, but will complain that the array key is not present in $ Wars. Of course, we can use isset (), but from Boilerplate issue also gets spoiled) Option 3 foreach ($ vars as $ key = & gt; $ value) {eval ("if (isset (\ $ key) & amp; amp; $$ Value) \ $ this- & gt; $ key = '$ value';);} (It works, it's clear, it's clear, it's clear Easily reusable, it adds any new class variables I add ... but it's eval (), and it gives me nightmares !:]) solution
Docherz Z indicated this but Melo responded. I did not hear about variable variables, but they actually did mer Were looking for. Gone for Inline: $ def_vars = get_object_vars ($ this); Forex Currency ($ Wars AS $ Key => $ Value) {If (array_key_exists ($ key, $ def_vars)) $ this-> {$ Key} = $ value; } However, anyone in the future should look for the answer to Johan PĂ©rez and do not use this snippet as a shortcut in the constructor. Should ... especially if the input array comes from the user's GET or Post parameters!
here you can
& lt ;? Php class name {public function __ composition ($ data) {foreach (data of dollar = $ as data = & gt; $ val} {$ this- & gt; {$ key} = $ val; }}}
Comments
Post a Comment