xhallix
xhallix

Reputation: 3011

PHP prevent instantiation of standard class

(this is just theoretical question, and is not intended to server as a good example)

lets say I write some kind of orm and all developers should use this class, is it possible to disallow the instantiation of certain std class in php, to make sure not other connection will be establish to this db?

E.g mysqli should not be able to be constructed.

Is this technical possible?

Thanks

Upvotes: 1

Views: 294

Answers (1)

Sebb
Sebb

Reputation: 911

There are several ways

... but none of it is perfect.

The easy way

If you don't want anyone to instanciate mysql/i, mongodbor the likes, you can simply unload the extension. Your ORM would need to use another connection class, then.

The hackish way

There's this nice extension called runkit which contains all the functions you should never use. It's possible to remove methods from classes so you might be able to overwrite the constructor of the class you wish to block. Do I need to mention that this is a really bad idea?

The good way

... are code reviews. You might think that those aren't really preventing someone from using mysqli, but:

  • You don't need to be doing worse things than your peers would do by circumventing the ORM.
  • You know who tried it and are able to explain to them why they shouldn't do this.
  • You're actually able to use the class. You might think now you never need it, but maybe your emergency logger shouldn't depend on your ORM. Oh, and by the way, your ORM needs to use it, too.

TL;DR

Properly review your code. It's part of a good coding style anyway, prevents bad solutions to force good solutions and allows exceptions if required.

Upvotes: 1

Related Questions