![]() |
Accessing Mysqli From Different Class
I'm just getting started with OOP and I'm having trouble connecting to the database.
I made a class that would allowed to connect to the database but I had to use 'global $mysqli' in every method to avoid the non-object errors. Now, I'm experimenting with a singleton pattern but I have no idea how to access the database connection from another class. Database class: PHP Code:
PHP Code:
$db = database::getInstance(); I'd really appreciate it if someone could point me in the right direction. :-) |
Quote:
PHP Code:
|
Only extend classes which will be children of that database object, for instance an SQL-Writer ( Part of an ActiveRecord, ORM Object ) would be a logical extension of a DAL object ( Though the argument could be made that the DAL object should just be fed into the SQL Writer but I digress ).
In this instance the issue seems to be that the object isn't being created in your getInstance() method. Also, I don't see the static instance property in your class. Hello-world, extending the database class would bear no fruit in this case because the __construct method creates the database connection and it is private ( I'm under the assumption that he would like to keep the current structure ) |
As you've already identified a solution, we might as well stick to it. That being the singleton pattern. This would work like so. With the following database class:
php Code:
And then we can use it like so from any other class we wish: php Code:
|
Quote:
|
for info - i ended up creating a singleton select pattern for db access. Using a static method check if an object has already been instantiated and if not then instantiate one.
I also extended the mysqli PHP delivered class to add a lot of extra functionality like class methods to start transactions of work, force rollbacks etc and also added a debug property so if its set to True i throw exceptions spilling out a lot of debug info and if False i throw a generic "having technical difficulties" exception. Reason I mention is I am using the same approach as yourself and found extending the mysqli class incredibly useful. |
| All times are GMT. The time now is 01:22 PM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0