Sometimes we prefer foreach for convenience and efficiency... In... structure to traverse data
The powerful array of PHP can meet our needs in most cases.
However, when the data structure defined by array cannot meet our needs, we have to write the iterator by ourselves.
For example, PDO provides bindparam to dynamically bind parameters, which can prevent injection and reuse of resources.
If you directly use the provided method, there is no defense. However, for most projects, you must have your own database operation layer.
How do I transmit dynamically bound parameters when encapsulating this db operation layer?
If array is used, only key, value, DB type, and so on can be provided (you can also use the delimiter, but it is too uugly)
To do this, we can customize the following classes:
ClassDbparam {...}// Represents a parameterClassDbparams {...}// Represents a set of parameters
Dbparam provides the parameter information required by bindparam, which is similar to the following:
Class dbparam {private $ _ key, $ _ value, $ _ type; // you can add the public function _ construct ($ key, $ value, $ type = PDO: param_str) {$ this-> _ key = $ key; $ this-> _ value = $ value; $ this-> _ type = $ type ;} public Function getkey () {return $ this-> _ key;} public function getvalue () {return $ this-> _ value;} public function getdbtype () {return $ this-> _ type ;}}
Dbparams is designed to use foreach... In... Traversal, because we willCodeUse it like this:
Function fetchxxx ($ SQL, lqp_dbparams & $ Params = NULL) {... $ stat = $ this-> _ DBH-> prepare ($ SQL); if ($ Params! = NULL) {foreach ($ Params as $ p) {$ stat-> bindparam ($ p-> getkey (), $ p-> getvalue (), $ p-> getdbtype () ;}$ stat-> execute ();....}
So how can we make dbparams support foreach? Generally, we can let it inherit the iterator interface and rewrite a large number of methods, which is too cumbersome. Here we directly let it inherit from iteratoraggregate:
Class dbparams implements iteratoraggregate {private $ _ Params = array (); Public Function add (lqp_dbparam $ PARAM) {array_push ($ this-> _ Params, $ PARAM );} // Implementation Method
Public Function getiterator () {return New arrayiterator ($ this-> _ Params );}}