No suggestions found for PDOStatement object returned through function

I'm trying to simplify my usage of PDO, but apparently PHPStorm gets lost somewhere.

Example:

$dsn = "mysql:host=123.456.789.123;dbname=whatever";
try {
/**
* @var PDO
*/
$dba = new PDO($dsn, $dbUsername, $dbPassword);
} catch (Exception $e) {
die("Unable to connect to database! Error #" . $e->getCode() . ": " . $e->getMessage());
}

$dsn = "mysql:host=123.456.789.123;dbname=whatever2";
try {
/**
* @var PDO
*/
$dbb = new PDO($dsn, $dbUsername, $dbPassword);
} catch (Exception $e) {
die("Unable to connect to database! Error #" . $e->getCode() . ": " . $e->getMessage());
}

function dbQuery($db, $query, $escape = array()) {
$query_result = $db->prepare($query, $escape); // should return a PDOStatement object
$query_result->execute($escape);
return $query_result;
}

$sql = "SELECT whatever FROM whatever";
$result = dbQuery($dba, $sql);

for either $dba or $dbb result statement objects.

 

4 comments
Comment actions Permalink

Hi there,

You need to typehint your dbQuery() function: at very least it should be either a return type or type of $db parameter (native typehint  or PHPDoc one)

 

(I've included false in return type. This depends on your PDO configuration -- if you configure it to emit exceptions on error or not)

1
Comment actions Permalink

Thanks, that appears to be working...

However, there's a few odd things in hover pop-ups now...

1. I'm not sure why the PDO specification is giving me a composer.json warning:

The repo has a composer.json file, but it's only used for one thing, unrelated to what I'm working with.

2. The suggestions are not alphabetized:

I can't even tell how it's sorting here...

0
Comment actions Permalink

>1. I'm not sure why the PDO specification is giving me a composer.json warning:

PDO is a custom extension that can be disabled in some setups.

The common trend nowadays is to mention all possible dependencies in composer.json (if your project uses it, of course).

This way, when somebody will use "composer install" with your project elsewhere and that extension is not available in that PHP installation it will give a warning/error right away instead of waiting for your code that uses it to be actually executed.

If you do not need it -- just disable that inspection. This can be done right from that popup --just use "More Actions" and then follow the extra menu for that entry:

 

>2. The suggestions are not alphabetized:

Must be your completion ordering settings, for example:

It can also be changed right from that popup:

 

I, for example, prefer that IDE lists most recently/frequently used entries at the top instead of A-Z order, e.g.

1
Comment actions Permalink

Andriy Bazanov - thank you for taking so much time to make this very clear.

0

Please sign in to leave a comment.