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.
Related
I have written a data class for handling MySQL queries and then all other classes such as login, products extend this class to make use of the database. As a result, each page load creates 2 or more DB connections due to something similar to the following:
$login, parent::__construct(); // check login via db
$products, parent::__construct(); // fetch products from db
Is there a way around this such as adding some code in the constructor to verify whether an existing DB connection has already been established?
A fellow developer I work with writes in procedural style and simply uses a single global $_db object for all queries and, this seems a lot more efficient as it only creates 1 DB connection.
For many smaller applications, I make my database instance global to the whole application, along with configuration and other application-wide classes, such as logging. This is not necessarily the preferred method, as it couples code to expect things named certain ways, and could possibly cause conflicts down the road. However, for small utility applications it is convenient.
For anything larger, I usually utilize my DB from an ORM anyway, so it becomes a non issue.
Michael's example of creating a static class and how to use it helped resolve the problem.
https://stackoverflow.com/a/26981461/541091
Please note I'm not looking for 'use a framework' answers. I'm trying to structurally improve the way I code websites and approach databases from PHP.
I'm building a web service from scratch, without any frameworks. I'm using a LAMP stack and am trying to learn a bit of PHP's OO functionality while I'm at it. I've previously only used OO to make mobile apps.
I've been at it for months now (as planned, no worries). Along the way I've bumped into a couple of structural problems, making me wonder what the best way would be to make the code object oriented.
Pretty much all of the problems involve the database in some way. Say we have a class DB and a class User. In most cases I only need to fetch a single user's information from the database. I thought a good way to handle it was to have a global $_db variable and have the User object query the database like so (oversimplified):
class User {
function __construct($id) {
global $_db;
$q = $_db->query("SELECT name, mail FROM user WHERE id = ?", $id);
$this->loadProperties($q);
}
}
Now say we have a page that shows a list of users. I still want to make User objects for each of them, but I don't want to query the database for each separate user.
So, I extend the User class to take an object as an argument:
class User {
function __construct($id) {
if(is_object($id))
$q = $id;
else {
global $_db;
$q = $_db->query("SELECT name, mail FROM user WHERE id = ?", $id);
}
$this->loadProperties($q);
}
}
Now I can create a list of, for example, the 100 most recently created and active accounts:
$user_list = [];
$q = $_db->query("SELECT name, mail FROM user WHERE banned = 0 ORDER BY date_created DESC LIMIT 100");
while($a = $_db->fetch($q))
$user_list[] = new User($a);
This all works great, except for one big downside: the database queries for table user are no longer in one place, which is kind of making spaghetti code. This is where I'm starting to wonder whether this can be done more efficiently.
So maybe I need to extend my DB object instead of my User object, for example:
class DB {
public function getUsers($where) {
$q = $this->query("SELECT name, mail FROM user WHERE ".$where);
$users = [];
while($a = $this->fetch($q))
$users[] = new User($a);
}
}
Now I would create the user list as follows:
$user_list = $_db->getUsers("banned = 0 ORDER BY date_created DESC LIMIT 100");
But now I'm calling the getUsers() method in various places using various SQL queries, solving nothing. I also don't want to load the same properties each time, so my getUsers() method will have to take entire SQL queries as an argument. Anyway, you get the point.
Speaking of loading different properties, there's another thing that has been bugging me writing OO in PHP. Let's assume our PHP object has at least every property our database row has. Say I have a method User::getName():
class User {
public function getName() {
return $this->name;
}
}
This function will assume the appropriate field has been loaded from the database. However it would be inefficient to preload all of the user's properties each time I make an object. Sometimes I'll only need the user's name. On the other hand it would also be inefficient to go into the database at this point to load this one property.
I have to make sure that for each method I use, the appropriate properties have already been loaded. This makes complete sense from a performance perspective, but from an OO perspective, it means you have to know beforehand which methods you're gonna use which makes it a lot less dynamic and, again, allows for spaghetti code.
The last thing I bumped into (for now at least), is how to separate actual new users from new User. I figured I'd use a separate class called Registration (again, oversimplified):
class Registration {
function createUser() {
$form = $this->getSubmittedForm();
global $_db;
$_db->query("INSERT INTO user (name, mail) VALUES (?, ?)", $form->name, $form->mail);
if($_db->hasError)
return FALSE;
return $_db->insertedID;
}
}
But this means I have to create two separate classes for each database table and again I have different classes accessing the same table. Not to mention there's a third class handling login sessions that's also accessing the user table.
In summary, I feel like all of the above can be done way more efficiently. Most importantly I want pretty code. I feel like I'm missing a way to approach the database from an OO perspective. But how can I do so without losing the dynamics and power of SQL queries?
I'm looking forward to reading your experiences and ideas in this field.
Update
Seems most of you condemn my use of global $_db. Though you've convinced me this isn't the best approach, for the scope of this question it's irrelevant whether I'm supplying the database through an argument, a global or a singleton. It's still a separate class DB that handles any interaction with the database.
It's a common thing to have a separate class to handle SQL queries and to keep the fetched data. In fact, it is the real application of the Single Responsibility Principle.
What I usually do is keep a class with all the information concerning the data, in your case the User class, with all the user information as fields.
Then comes the business layer, for instance UserDataManager (though the use of "Manager" as a suffix is not recommended and you'd better find a more suitable name in each scenario) which takes the pdo object in its constructor to avoid use of global variables and has all the SQL methods. You'd thus have methods registerNewUser, findUserById, unsuscribeUser and so on (the use of "User" in the method can be implied by the class name and be omitted).
Hope it helps.
I've liked to use the data mapper pattern (or at least I think that's how I'm doing it). I've done this for some sites built on Silex, though it's applicable to going without a framework since Silex is very lightweight and doesn't impose much on how you architect your code. In fact, I recommend you check out Symfony2/Silex just to get some ideas for ways to design your code.
Anyway, I've used classes like UserMapper. Since I was using the Doctrine DBAL library, I used Dependency injection to give each mapper a $db. But the DBAL is pretty much a wrapper on the PDO class as far as I understand, so you could inject that instead.
Now you have a UserMapper who is responsible for the CRUD operations. So I solve your first problem with methods like LoadUser($id) and LoadAllUsers(). Then I would set all the properties on the new User based on the data from the database. You can similarly have CreateUser(User $user). Note that in "create", I'm really passing a User object and mapping it to the database. You could call it PersistUser(User $user) to make this distinction more clear. Now all of the SQL queries are in one place and your User class is just a collection of data. The User doesn't need to come from the database, you could create test users or whatever else without any modification. All of the persistence of `User is encapsulated in another class.
I'm not sure that it's always bad to load all of the properties of a user, but if you want to fix that, it's not hard to make LoadUsername($id) or other methods. Or you could do LoadUser($id, array $properties) with a set of properties taht you want to load. If your naming is consistent, then it's easy to have set the properties like:
// in a foreach, $data is the associative array returned by your SQL
$setter = 'set'.$property;
$user->$setter($data[$property]);
Or (and?) you could solve this with Proxy objects. I haven't done this, but the idea is to return a bunch of UserProxy objects, which extend User. But they have the Mapper injected and they override the getters to call into the Mapper to select more. Perhaps when you access one property on a proxy, it will select everything via the mapper (a method called populateUser($id)?) and then subsequent getters can just access the properties in memory. This might make some sense if you, for example, select all users then need to access data on a subset. But I think in general it may be easier to select everything.
public function getX()
{
if (!isset($this->x)) {
$this->mapper->populateUser($this);
}
return $this->x;
}
For new users, I say just do $user = new User... and set everything up, then call into $mapper->persist($user). You can wrap that up in another class, like UserFactory->Create($data) and it can return the (persisted) User. Or that class can be called Registration if you'd like.
Did I mention you should use Dependency Injection to handle all of these services (like the Mappers and others like Factories maybe)? Maybe just grab the DIC from Silex, called Pimple. Or implement a lightweight one yourself (it's not hard).
I hope this helps. It's a high-level overview of some things I've picked up from writing a lot of PHP and using Syfmony2/Silex. Good luck and glad to see PHP programmers like yourself actually trying to "do things right"! Please comment if I can elaborate anywhere. Hope this answer helps you out.
You should first begin by writing a class as a wrapper to your Database object, which would be more clean that a global variable (read about the Singleton Pattern if you don't know it, and there is a lot of examples of Singleton Database Wrapper on the web). You'll then have a better view of the architecture you should implement.
Best is to separate datas from transactions with the database, meaning that you can for example have two classes for your User ; one that will only send queries and fetch responses, and the other that will manage datas thanks to object's attributes and methods. Sometimes, there can be also some action that doesn't require to interact with the database, and that would be implemented in these classes too.
Last but not least, it can be a good idea to look a MVC frameworks and how they work (even if you don't want to use it) ; that would give you a good idea of how can be structured a web application, and how to implement these pattern for you in some way.
This question might sound strange, but I have a simply tiny session-based login system (PHP+MySQL) for one of my projects, and I was wondering if it would make any sense to store a user in an object. I could imagine such situations, where doing this could be useful, but... I don't really know. Does it make difference in case of let's say a microblogging system?
I think there could be a User class defined, with properties loaded from the MySQL tables, and it could have methods/functions like getUserName() or logOut() or addPost().
The top reason I asked myself this question, is that I don't have a single clue about how to pass an object to the session, plus all this object-oriented stuff is a little bit new for me as well. I'm not entirely sure about when to think with OOP and when to not.
If you could give me some advices about the topic, or anything useful, it would be extremely helpful. Thanks! :)
Since there is no significant overhead for objects in PHP 5.3/5.4, I would recommend you to write code in object oriented style for everything, except simple experiments in codepad.
As for the authentication system, i wold split it up in two parts:
domain object, that contains all of your user validation logic
data mapper, that can save User instance to DB
Here is a simple API example that you might try to use as basis for your code:
$user = new User;
$mapper = new UserMapper( $pdo );
$user->setName( $_POST['username'] );
$mapper->fetch( $user );
if ( $user->isAvailable() && $user->matchPassword( $_POST['password'] ))
{
$user->setLastLogin( time() );
// here you put interaction with session
}
else
{
$user->addFailedAttempt();
if ( $user->getAttempts() >= 5 )
{
$user->setStatus( User::STATUS_LOCKED );
}
}
$mapper->store( $user );
You have to understand that the aim of OOP is the maintainability and readability of the code. I assume that you can figure out what goes on in that code snipped without seeing the exact implementation of each method.
Using classes will make your code more readable and easier to change/modify/upgrade. Also it will reduce code size. But you can also define does functions in a php file without having a class or OOP, just functions and include them everytime you need them. If you use classes it will be easier to pass data in entire web application between functions, entire user object will be as an object. Classes has no effect in performance at all. That's all I have to tell for now.
First of all to answer your question: I would store only those information needed to find the user in the database. If you can load it through your database you could also instantiate a new user object each request which I think is better because data could change and if user data changes you have to update your database AND your session. So load your user from database and create an instance on each request.
Second: Take a look at some sort of orm (Object-Relational-Mapping system) like doctrine2 or similar. Those systems do exactly what you want with your user object.
I'm creating a new PHP application and want to make sure I get the ground work right to save any future problems. I know my application will have more than one class that will need a database connection (PDO) and after a long time scouring the internet i can't find a definitive solution.
I like the singleton design pattern personally, but there are a lot of people out there that say singletons in general should be avoided at all costs. These people, however, don't give a specific solution to this problem.
I understand that an application may need more than one database connection but could i not create a singleton that contained each required DB connection (i.e. DB::getInst('conn1')->query(); )?
Is it a case of having to pass round the PDO (or PDO wrapper) object to every class that may need it? I've done this before found it annoying keeping track of it.
I personally thing a singleton (or a multiton, if you need several DB connections) is fine for such an usage.
But if you do not want to use it, you should then take a look at the Registry pattern.
This way, you can have your database class instance(s) available for all your application's classes, without having to pass an additional parameter each time (which is very ugly, IMHO).
but could i not create a singleton that contained each required DB connection (i.e. DB::getInst('conn1')->query(); )?
you can, it's called multiton pattern
This is going to take a bit to explain. I'm creating my first real-world web application, and I'd to do it properly. I have very little PHP experience, but vast experience in other languages so technical skill isn't a problem, it's more conventions of the language. I'm following the MVC pattern, and I am at the stage where I'm implementing user registration for the application.
To standardise connections to the database, I've created a Config class with a static getConnection method, which creates a mysqli connection object. This isn't a problem, it's the next bit that is.
To make my classes a bit more readable, I have various functions built into them that make database calls. For example, my User class has a getFriends method like so:
class User
{
public $id;
public getFriends()
{
return UserController::getFriends($id);
}
}
But as it stands now, if I implement it that way, it means creating a connection for every query on a page, probably many times in a single script, which is just horrific.
I was thinking about doing the same as above, but pass getFriends a mysqli object, which in turn passes one to UserController::getFriends as well, but that feels messy, and frankly poor form, even though it would guarantee only one connection per script, a much better improvement.
I also thought about scrapping the idea of keeping the methods inside User altogether, and instead making calls like UserController::getFriends($connection, $id) directly in the script, with a single $connection declared at the beginning, in place of user->getFriends(). That seems like the absolute cleanest, nicest solution, but I'm unsure.
So, essentially, how do PHP folks normally do this sort of thing?
What I do in my MVC framework is create a db connection and assign it to the Model base class (in the config):
$db = new database\adapters\MySQL(...);
if ( !$db->connected() ) {
exit('Ewps!');
}
database\Model::dbObject($db);
Then later on, anywhere, I can use:
User::getFriends(13);
because User extends Model and Model has access to $db: self::dbObject()
If I need my raw db connection, I either use Model::dbObject() or $GLOBALS['db'], but I rarely do need the raw connection, because all db logic should be in your Models.
https://github.com/rudiedirkx/Rudie-on-wheels/blob/master/example_app/config/database.php
https://github.com/rudiedirkx/Rudie-on-wheels/blob/master/example_app/models/User.php#L30
Have a look into the Singleton Pattern . It allows you to create a class (a DB object), but where only one of them is ever allowed (so more than one can't be instantiated).
This means that you only have to create one connection to the DB and it's shared.
Check here for a code example