Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

So here's the gist of it. I'm looking for a design pattern where I can have one function, say queryHandler that gets the query and the parameters from a number of different functions and returns the said query results.

At the moment, I have a Core class which implements the singleton pattern for database object creation and so forth.

However, I want a design pattern that can handle different queries with different bind parameters. So, take these queries:

SELECT * FROM foo WHERE id = :bar

INSERT INTO foo (id, name, bar) VALUES (:id, :name, :bar)

Etc.

For the first one, I would have a bindParam where :bar would be PDO::PARAM_INT, however, in the second case it would be multiple bindParams with both INT and STR types.

I want my functions to just have one variable, and one call to the queryHandler:

$query = 'SOME QUERY HERE'
$this->queryHandler($query, $params ... or something)

Obviously, queryHandler would sort out how many params, their type, and do the query itself.

Any ideas? Thanks

share|improve this question
    
That smells like an SRP violation. Perhaps you might be better looking at the repository pattern and data access objects –  AndyBursh Mar 12 at 16:10

1 Answer 1

Use a multidimensional array like $key => $value, $key2 => $value2 and iterate?

$data = array( 'column_name' => 'value' );
querysorter ( 'tblname', $data );
function querysorter{
foreach($data)
//bindparam here
}

Hope this helps, just had to do something similair.

share|improve this answer
    
how would you sort between the difference type of params? ie INT vs STR? –  fizzy drink Feb 10 at 15:44
    
PHP does that for you, could you give me an example? –  Robert Pounder Feb 10 at 15:54
    
@RobertPounder No, PHP does not do that for you. Have a look at the documentation: php.net/manual/de/pdostatement.bindparam.php PHP requires you to provide a format constant which denotes in which format the parameter should be transfered. If omitted, it will transfer it as a string. This does work in most cases, but not when it would result in an ambiguous type cast (e.g. because MySQL would accept both a string as well as an integer as first parameter to a certain function). –  Ext3h Apr 11 at 19:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.