开发者

PHP conventions for encapsulation and database calls

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 d开发者_如何学Pythonatabase 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜