I'm trying to make a small cms in php and mysql, and want it to be object-oriented
I have a class DbConnector that handles all sql queries. Then I have some other classes that needs to alter the database through the DbConnector.
As I see i I have to either send the DbConnector instance as a parameter in every class initialization, or I can make a new DbConnector instance for each class, which to me seems pretty unnecessary.
What is the preferred way to do this or is it all wrong?
The preferred way of doing this would be Dependency Injection, the lazy / easy / OK for small scale way could be a Singleton database object.
Related
I have a script comprising lots of classes. In the classes' functions numerous mysql operations are carried out. I want to use a single datebase handle throughout the script. Thus, the Singleton approach or dependency injection (DI) might do this job.
However, I am wondering if I am right that using Singleton is the more efficient way from a maintainance point of view:
Assuming that all my (parent) classes finally extend the singleton class. Thus, in order to change something with respect to obtaining the database handle, I only need to do amendments to the singleton class. Particularly, I do not have to make any thoughts when adding new classes or the like since the database handle will be always present by extending the respective class of the Singleton class.
In contrast, when using DI I must provide code for creating the database handle in every script which might serve as a starting point (and passing the handle to the instances created). E.g. in script1.php, script2.php, script3.php, etc. Thus, amendments which should be made to the way the database handle is obtained must be made in every script, script1.php, script2.php, script3.php, etc..
The former approach looks much nicer to me in this respect than the latter. Or do I oversee some important thing?
When I first saw dependency injection components like PHP-DI, Symfony2 DI, etc., I though, there is a way to automatically inject instance of any class to any just with one instantiation.
So
1. Create instance in root class like $foo = new Foo()
2. And then I can use this instance in any object (like global singleton) without passing reference to constructor or method of the class I want to call from.
But I found out, that basicly I can use Dependency Injection in 2 ways
1. Passing the reference of the instance to constructor
2. Creating container where all objects are located. This container could be injected to other classes, but "This is not recommended".
As both ways can be easily done in pure PHP, the first is clear, the second could be solved with static properties, so why to use PHP-DI or Symfony2 for this work?
Why should you use Dependency Injection over the Singleton pattern?
Let's assume we have a Singleton object named DatabaseConnection which wraps a connection to a MySQL database for us and does some other neat things, who knows. Because reusing code is a good thing, we use this object in a lot of projects.
What if at some point we decide to switch one of our projects from MySQL to another database product? We would have to modify every place where we call the DatabaseConnection object and replace it with our new implementation. Or, we could modify the class itself -- but we still want to use the original one with other projects, so we end up with two implementations with the same name which is just asking for trouble, really.
And what about unit tests? We do those, of course, because we are good developers! But if we unit test a function that uses the database, we don't want the test to actually rely on the database or even change things there. There's no way to replace the DatabaseConnection with a mock object (that just returns static data) because our project is tightly coupled to it.
That's what Dependency Injection does: It helps to prevent tight coupling. If we inject the connection with $someObject->setDatabaseConnection($databaseConnection), we can inject any object there that behaves like the original one. We can inject mock objects, alternative implementations or extensions that inherit the original class.
Now a Dependency Injection Container is just a nice helper to manage object instances and their dependencies more easily, but it's not needed for doing Dependency Injection.
Object oriented programming is a so high abstract level that sometimes I must to put in doubt my own conviction about the class I'm just creating. Well, I have made some research over some books and internet sites about the question if it is a good practice to use return inside __construct function. So far, I use __construct only to initialize objects. Is there a good site where I could find pros and cons about this, and showing examples? Now I am using php.
Constructor only purpose is to create an instance of a class.
You should think of constructor a way to prepare the object for use, nothing is returned, all you do is create an instance of a class.
I've done mostly procedural programming for years and am trying to wrap my head around OOP and PDO. I've started converting an application I've written to using classes instead of standalone functions (it's a nightmare, but I think it will be worth it..) and would like to use PDO instead of the regular mysql_* functions. I'm kind of flying by the seat of my pants, just learning as I go along, and I'm not sure how I should handle the PDO object(s).
I know it would be stupid to create a new PDO object every time I need to make a query, so that leaves two ways that I can see:
Creating a PDO object in each class (i.e. every time an object is created, call a member function to create a PDO for it to use).
Create PDO object at the beginning of my application and pass it to the constructor of every object that is created, and all the objects share the PDO object.
What is the best way to do this?
Thanks for your advice!
Don't make more than one. You'll go crazy trying to manage all the DB connections.
One good solution would to make a singleton object for data access and retrieve it via it's static accessor method whenever you want to use the DB. That way you only ever have one place that manages DB access and PDOs. If you want to be a bit more MVC about it, you can put all SQL code in there too.
Depending on the size of the application, you probably want to use a Singleton to handle your database connection. Essentially, this will be a class that wraps your database connection and has a static function that will return your PDO object. However, because it's a Singleton it will only ever create one (assuming you don't make it more sophisticated). This saves you both from having to continuously make objects and from having to pass one object into all your objects, properly decoupling persistence from business logic.
I've got a PHP function (call it funcA) that is used in multiple places, so I placed funcA (and some related functions) in a separate file that is required in other PHP files. funcA makes numerous queries on a database that is already open and used by the code that calls it. Those queries are done via an MDB2 object.
As it stands now, where funcA is called, the calling routine passes an already-connected MDB2 object pointer to it. This works fine.
What I'm wondering is if it would be better to make funcA completely self-contained by not passing the MDB2object pointer and instead having funcA require MDB2 and connect to the database with its own mdb2 object. It's more memory, more CPU cycles, and more network traffic, but is it a better practice?
"best practice" is one of those things that are almost impossible to define. However, in my view, where a function depends on something else, it's best to pass that dependency into the function - as you're doing now.
This allows your function to do whatever it does, without having to worry about finding and connecting to the database. It also allows you to test your function with a dummy database.
It's generally known as dependency injection, and widely recommended in object oriented architectures.
Some might call it bad practice too but a solution in this situation might be the Registry pattern or a Singleton PDO class.
I don't want to start a whole discussion on the right and wrong of singletons or registries but in this case it might be the cleanest solution that doesn't involve refactoring a large part of your application.
Some really basic examples (you should really read up on the links above since understanding these patterns can save you alot of time and trouble)
// Singleton class MyPDO
// This assumes you have a singleton class extending PDO somewhere included or required
function funcA(){
$database = MyPDO::getInstance();
// ...
}
// Registry pattern
// This assumes that somewhere during your bootstrapping you create an
// instance of PDO and store it in the registry so you can retrieve it
// anywhere else later
function funcA(){
$database = Registry::get('Database');
// ...
}