如何在PHP上使用DAL

Hello i have a code where they use this to connect to database

$db= DAL::get_instance();           

$count=$db->read_single_column("select count(id) from ".TABLE_PREFIX."users where email=? and status=1", array($email));
 echo "Aqui".$count;

I make a blank new page for that site, but i think $db= DAL::get_instance(); is not working.. i dont want to create multiple Connections to database, so how can i use DAL on PHP so i can use that same chain to connect...

And where and how is set DAL? (how can i search for the string where is set, whats the format)

Thanks

I Found a DAL.php on the library core.. But its encripted with Ioncube.. so my guess is i wont be able to see how is set :(

Your DAL class is userland-defined - there is no such thing in PHP. Post the entire code of it somewhere and someone might be able to tell you what to do with it.

I will, however, provide generics based on what you've said. static::get_instance() and the mention that you are not able to fire more than one instance of it suggests that your database abstraction layer is, in fact, a Singleton. This is good, and then again, this is very bad. The entire aim of the Singleton is to restrict the class to one and one instance only, which is quite nice for a database layer.

In your case, however, it looks like you want to connect to multiple DBs at the same time. Depending on how the code is coded, you may be able to do this with little to no modification to the code.

For reference, this is a simplified version of your DAL: http://codepad.viper-7.com/gPQ8bo . I kept the bits you are concerned with and stripped everything else out.

The obvious way

Rip up the singleton and start using dependency injection.

The not-so-obvious way

You can use Reflection to reset a Singleton's private static member. This is a hack, so use only if you have to.

The fiddle to this lies here: http://codepad.viper-7.com/ja6zHL . The code is as follows:

$reflection = new \ReflectionProperty('MySingleton', 'instance'); // Get a handle to the private self::$instance property
$reflection->setAccessible(true); // Set it to public
$reflection->setValue(null, null); // Modify it
// Optional: re-restrict it
$reflection->setAccessible(false);

Note that this is hackish for three reasons:

  • You should not be doing this. Instead, you should consider using a DAL that actually allows you to fire multiple connections or make one yourself
  • This uses Reflection, which has pretty big performance implications
  • This is a hack. You also lose your first DB connection, so you need extra housekeeping.