Database and OOP Practices in PHP - php

Its difficult to explain this situation but please see the example.
I have coded a website where the page loads, I initialize a database class. I sent this class as a function parameter to any functions that needs to access database.
I know this is bad approach but currently I have no clue how to do this any other way. Can you please help me.
Example
class sms {
function log_sms($message, $db) {
$sql = "INSERT INTO `smslog` SET
`mesasge` = '$message'
";
$db->query($sql);
if ($db->result)
return true;
return false;
}
}
then on the main page..
$db = new db(username,pass,localhost,dbname);
$sms = new sms;
$sms->log_sms($message, $db);
Is there any better approach than this ?

there are number of options how to resolve dependencies problem (object A requires object B):
constructor injection
class Sms {
function __construct($db) ....
}
$sms = new Sms (new MyDbClass);
setter injection
class Sms {
protected $db;
}
$sms = new Sms;
$sms->db = new MyDbClass;
'registry' pattern
class Registry {
static function get_db() {
return new MyDbClass;
}}
class Sms {
function doSomething() {
$db = Registry::get_db();
$db->....
}}
'service locator' pattern
class Loader {
function get_db() {
return new MyDbClass;
}}
class Sms {
function __construct($loader) {
$this->loader = $loader;
function doSomething() {
$db = $this->loader->get_db();
$db->....
}}
$sms = new Sms(new Loader);
automated container-based dependency injection, see for example http://www.sitepoint.com/blogs/2009/05/11/bucket-is-a-minimal-dependency-injection-container-for-php
interface DataSource {...}
class MyDb implements DataSource {...}
class Sms {
function __construct(DataSource $ds) ....
$di = new Dependecy_Container;
$di->register('DataSource', 'MyDb');
$sms = $di->get('Sms');
to name a few ;)
also the Fowler's article i gave you before is really worth reading

For starters you can make a protected $db variable in each of your classes that need to utilize the database. You could then pass $db in to the class constructor. Here's the updated code:
$db = new db(username,pass,localhost,dbname);
$sms = new sms($db);
$sms->log_sms($message);
class sms {
protected $db;
public function __construct($db) {
$this->db = $db;
}
public function log_sms($message) {
$sql = "INSERT INTO `smslog` SET
`mesasge` = '$message'
";
$this->db->query($sql);
if ($this->db->result)
return true;
return false;
}
}
This example is in PHP 5.

Singleton is also good practice in application design. They are very useful to avoid repeated queries or calculations during one call.
Passing Database object to every method or constructor is not a very good idea, use Singleton instead.
extend your database, or insert static method inside your db class. (I would also call for config within db constructor method)
class database extends db
{
public static function instance()
{
static $object;
if(!isset($object))
{
global $config;
$object = new db($config['username'],$config['pass'],$config['localhost'],['dbname']);
}
return $object;
}
}
make your method static
class sms {
public static function log($message) {
$sql = "INSERT INTO `smslog` SET `mesasge` = '$message'";
database::instance()->query($sql);
return (bool) database::instance()->result;
}
}
Next time you need to log sms just do static call like this
sms::log($message);

You could either have a static class that has two lists, one of available connections, the other of handed out connections, and just have a connection pool.
Or, if you are using something that has a quick connection time, such as MySQL, then just create the connection in your database class, do all the queries needed for that functionality, then close it. This is my preferred approach.

Related

Singleton v Single Instance DB Connection in PHP

I'm moving onto teaching myself OOP in PHP.
I'm creating a couple of little web apps and have followed a lot of tutorials that either create the database (using PDO) via a Singleton, or via passing the global around. I've read that these are pretty much the same thing and are both to be avoided like the plague.
So I've watched the Google Tech Talks on clean code, and read almost every SO article on dependency injection and the like. I have a couple of questions.
The clean code videos suggest you shouldn't do 'work' in your constructors. Is this 'work' in reference to business logic. Ie. If my class's job is to create another object, is that an OK kind of 'work'?
For example, in trying to conform to single repsonibility classes I created three.
Class DB - which actually connects to the database.
Class DBFactory - which creates the DB object which connects to the database.
Class DBInstance - which returns a single instance of the DBFactory created PDO object.
Please note that I'm trying to create a single instance, without creating a Singleton pattern.
So I try and pass my dependencies for each class up the chain. I find myself in a position where I have to create all of the objects (from DB down) so I can inject the dependencies. For some reason I thought it would work the other way, I'd create the first object, which would create the second for me etc. I'm clearly missing something?
Hopefully this helps others as well - there seems to be a myriad of questions relating to this stuff and databases but very little good examples.
(I should mention this does work, I do get a list of hotel names out of the database!)
TestCode.php
include './classes/DB.php';
include './classes/DBFactory.php';
include './classes/DBInstance.php';
include './classes/Location.php';
$db = new DB;
$dbfactory = new DBFactory($db);
$dbinstance = new DBInstance($dbfactory);
$dbh = $dbinstance->getDbInstance();
//Example business logic
$location_names = Location::getLocationNames($dbh);
print_r($location_names);
Class DB.php:
class DB {
private $_dbhost = 'myhost';
private $_dbname = 'myname';
private $_dbuser = 'myuser';
private $_dbpass = 'mypass';
private $_error;
public function connect() {
try {
return new PDO("mysql:host=$this->_dbhost;dbname=$this->_dbname",
$this->_dbuser, $this->_dbpass);
}
catch (PDOException $e) {
$this->_error = 'Error! ' . $e->getMessage() . '<br />';
die();
}
}
public function getError() {
if (isset($this->_error)) {
return $this->_error;
}
}
}
Class DBFactory.php
class DBFactory {
private $_dbh;
public function __construct(DB $db) {
$this->_dbh = $db;
}
public function Create() {
return $this->_dbh->Connect();
}
}
Class DBInstance.php
class DBInstance {
private static $_dbinstance;
public function __construct(DBFactory $dbfactory) {
if (!isset(self::$_dbinstance)) {
self::$_dbinstance = $dbfactory->Create();
}
}
public function getDbInstance() {
return self::$_dbinstance;
}
}
Your code seems to do what you want it to.. but maybe we can use less object instantiation using inheritance and maybe we can avoid static properties in instanciated classes.
Also in regard to using a pattern of dependency injection that is able to handle multiple connections, but support using a single instance of it. exemple first, classes after
$params = array
('host'=>'localhost',
'db'=>'ice',
'user'=>'kopitar',
'pass'=>'topnet',
'charset'=>'utf8'); // passing the charset explicitely is great
$handle = new handle($params);
$db = $handle->getInstance();
we can either pass the $db to our functions
$location_names = Location::getLocationNames($db);
or the whole $handle. as long as $handle is not reconstructed, it will always return the same database connection.
$location_names = Location::getLocationNames($handle);
if I want to reconstruct I need the whole $handle
$handle->__construct(/* params but with another database infos */);
$db2 = $handle->getInstance();
As for the classes, I think we want the params to arrive from the instanciated class, so we can change them later.
class db {
function __construct($params) {
foreach ($params as $param => $value) {
$this->{$param} = $value; // assigns the connections infos
}
}
protected function connect() {
$dsn = 'mysql:host='.$this->host.';dbname='.$this->db.';charset='.$this->charset;
return new PDO($dsn,$this->user,$this->pass);
}
}
the factory creates a connection from params and passes it to something else, good factory
class factory extends db {
protected function create() {
return $this->connect();
}
}
now we want to have our object to keep it's connection as long as we do not rebuild it. so we give it to instance
class instance extends factory {
function instantiate() {
$this->instance = $this->create();
}
}
and last but not least, our handle which returns the instance. it could be in instance class.....................
but I feel like having four and find no real reason not to.
class handle extends instance {
function __construct($params) {
db::__construct($params);
$this->instantiate(); // when we construct a handle, we assign an instance to the instance property
}
function getInstance() {
return $this->instance;
}
}
KISS
Don't make things more complex than they are, of course this is just my opinion, but as I see it you are building a complex solution for a problem that someone else says might exist is some cases.
Php is not multi threaded so there goes one of the biggest arguments overboard. (in very rare-occasions it might be)
I'm using singletons for my database connections for about 15 years now and never ever had a problem with them, I do play around with different connections having one singleton handle several connection instances, but whatever... it works great and everyone that looks at the code.. understands it directly.
I'm not using globals because they can be overwritten and are kind of hard to predict (when it holds the correct object, and when/why they don't)
Use OOP to make your code cleaner, easier to work with and more flexible.
Don't use it to fix problems that aren't there and make your code more complex because others tell you to.
An very simple example of a db-connection singleton class handling several different connections.
class singleton{
private static $_instances=array();
public static function getInstance($connectionName){
if(!isset(self::$_instance[$connectionName]){
self::$_instance[$connectionName]=self::_getConnection($connectionName);
}
return self::$_instance[$connectionName];
}
}
just my 2 cents
Why do you have a factory if you have a singleton? This is needless.
This is a never-ending debate, but I'm advocate of do not use singletons for database connections.
As far as in most applications, you have only one data channel, you can consider your database connection unique, but this might not be always true.
In deed, the effort made to create a singleton database connection is even bigger than just create a regular one.
Also, your class DB is not configurable, therefore, you need to change it when your connection parameters change. And I think DB is a very bad name for this.
I'd rather call this Storage and do something like:
inteface Storage {
public function insert($container, array $data);
public function update($container, array $data, $where);
public function delete($container, $where);
public function getAll($container);
public function getOne($identifier);
}
final class PdoStorage implements Storage {
private $dbh;
private $dsn;
private $user;
private $pswd;
public function __construct($dsn, $user, $pswd) {
$this->dsn = $dsn;
$this->user = $user;
$this->pswd = $pswd;
}
// Lazy Initialization
private function connect() {
if ($this->dbh === null)
$this->dbh = new PDO($this->dsn, $this->user, $this->pswd);
}
public function insert($container, array $data) {
$this->connect();
// ... omitted for brevity
}
}
Now, when you need a database storage, you do:
$someObj = new SomeClass(new PdoStorage(...));
Now you might be wondering if you will need to create an PdoStorage for each single object that depends on it.
The answer is: no!
Now you can use a factory to simplify your life.
class SomeFactory {
private $defaultStorage;
public function __construct(Storage $storage) {
$this->defaultStorage = $storage;
}
public function create($type) {
// Somehow fetches the correct class to instantiate and put it into $class variable , for example... and then
return new $class($this->defaultStorage); // Or you'd better do this with reflection
}
}
$factory = new SomeFactory(new PdoStorage(...));
$factory->create('SomeClass');
This way, you can have just one database connector or more if you need.

OOP efficiency when using a class in another class

I have a class called DB (class.pdo.php) that does all the handling on mysql queries using PDO and another class called user that I use to manage a login system.
My question relates to always having to instantiate the $db in every public function of users so I can use DB. Is this efficient? Shouldn't I be instantiating DB inside the __construct() of users?
This is my code
require_once("../../class.pdo.php");
class user {
private $db = null;
public function __construct(){
/* Empty? */
}
public function find_by_email($email){
$db = new db();
$db->query('SELECT * FROM users WHERE email = :email LIMIT 1');
$db->bind(':email',$email);
$result = $db->single();
return $result;
}
public function create($email,$password,$first_name,$last_name){
$db = new db();
$db->query("INSERT INTO users(email,password,first_name,last_name,created_at) VALUES (:email,:password,:first_name,:last_name,NOW())");
$db->bind(':email',$email);
$db->bind(':password',$password);
$db->bind(':first_name',$first_name);
$db->bind(':last_name',$last_name);
$result = $db->execute();
return $db->lastInsertId();
}
[more similar functions ommited]
Well, despite of some comments suggesting the use of the Singleton pattern, I totaly disagree in using it for this purpose.
Your application will not always use a single connection to just one database.
Let me show you how I'd do this:
class DbConnector {
private $dbh;
private $dsn;
public function __construct($dsn) {
$this->dsn = $dsn;
}
private function connect() {
if($this->dbh === null) {
$this->dbh = new PDO($this->dsn);
}
}
public function disconnect {
if($this->dbh !== null) {
$this->dbh = null;
}
}
public function query($sql) {
$this->connect();
//... do the rest
}
public function fetchAll($sql) {
$this->connect();
//... do the rest
}
public function insert($table, $values) {
$this->connect();
//... do the rest
}
public function update($table, $values, $cond) {
$this->connect();
//... do the rest
}
public function delete($table, $cond) {
$this->connect();
//... do the rest
}
}
class User {
private $dbConn;
public function __construct(DbConnector $dbConn) {
$this->dbConn = $dbConn;
}
public function create($email,$password,$first_name,$last_name){
$this->dbConn->query("INSERT INTO users(email,password,first_name,last_name,created_at VALUES (:email,:password,:first_name,:last_name,NOW())");
$this->dbConn->bind(':email',$email);
$this->dbConn->bind(':password',$email);
$this->dbConn->bind(':first_name',$email);
$this->dbConn->bind(':last_name',$email);
$this->dbConn->execute();
return $this->dbConn->lastInsertId();
}
// ...
}
Results:
No singleton used = testable.
Connection to the database is just openned when needed
Your connection is persistent. If you open and close connections in every method, you loose the capability of creating transactions.
What about using the Singleton pattern to create one object for the connection and use it everytime you need it, instead of creating new objects all the time?
I would do something similar with lazy loading: don't initiate in the constructor unless you're sure you actually need the connection every time an object is created but absolutly don't create a new object on each method call. Instead, save the resulting object into an object var which is checked on each method call and initiates the connection if missing.
class user {
protected $_db = null;
private function _init_db() { $this->_db = new XXX; }
public function create( $x, $y, $z ) {
if ( ! $this->_db ) $this->_init_db();
# use $this->_db ..
}
public function find_by_email( $x, $y, $z ) {
if ( ! $this->_db ) $this->_init_db();
# etc
}
}
This has the advantages of avoiding global static state (singletons..) and only creates the connection / object at the very last moment so you're sure you actually need it and it's not just a useless connection.
Speaking of efficiency, the main problem with your code is that it establishes new connection for the every method called. This one is indeed inefficient to the point of killing your database server. And it's incomparable to the other problem you have.
So, in general, you can have whatever way you want - either get somehow an instance of db class in the every function or use a class variable - but either way have to use single PDO instance throughout whole application.
Also I find your functions quite inefficient from the amount of code point of view, and would have optimized them this way
public function create($email,$password,$first_name,$last_name){
$sql = "INSERT INTO users(email,password,first_name,last_name,created_at) VALUES (?,?,?,?,NOW())";
$this->db->query($sql);
$result = $db->execute(func_get_args());
return $db->lastInsertId();
}
From a object point of view, I'd leave database instantiating within the methods, rather than an entire class.
Each method should only see the variables and data it needs, in order to perform its function.
For instance, a createUser() method would need to see variables or properties such as $username, $usergroupId, as well as $database etc.
However, you may have a function which is called randomPassword(), which generates a random password from numbers and letter.
This randomPassword() function doesn't need the database object and therefore, an already initialised database connection in the object scope would be wasteful.
It would be better only to create the new database object in methods that required it.
In addition, in my application, I don't create a new database connection each time I used new database. Instead, I've opted for a singleton PDO database object which keeps the connection active.
I can then just call the database object statically to retrieve an existing connection. Therefore, if, in the process of running my application I need to have 20 database objects, my application then only returns the same object, and the same connection.

Assistance with OOP, PDO Shopping Cart Class [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the best method for getting a database connection/object into a function in PHP?
Database and OOP Practices in PHP
I am trying to build an OOP shopping cart.
At present, it is half OOP, and half procedural... e.g.
function removeFromCart() {
require_once('/.../.../connectPDO.php');
$db = connectPDO();
$sql = 'DELETE FROM Quotes WHERE User = :user and ProductId = :pid';
$stmt = $db->prepare($sql);
$stmt->execute(array(':user' => $user, ':pid' => $pid));
}
My problem is that if I wish to add to cart, then in my function addToCart, I will need to require the db connection again.
This seems like a complete waste, considering every function will need to contain the following:
require_once('/.../.../connectPDO.php');
$db = connectPDO();
I am aware that this is completely in-efficient, and was wondering if anybody could help me write a skeleton OOP cart class which uses the above connection to connect to the DB?
Does this go in the constructor??? Will this stay alive when a user navigates from one page to another at the front end?
I am new to OOP and am completely lost.
Many thanks in advance.
Something like the following should get you started:
$pdo = new PDO('your dsn');
$cartData = new CartData($pdo);
$cart = new Cart($cartData);
class CartData
{
private $dbConnection;
public function __construct(PDO $dbConnection)
{
$this->dbConnection = $dbConnection;
}
public function removeItem($userId, $productId) {
$sql = 'DELETE FROM Quotes WHERE User = :user and ProductId = :pid';
$stmt = $this->dbConnection->prepare($sql);
$stmt->execute(array(':user' => $userId, ':pid' => $productId));
}
}
class Cart
{
private $cartData;
public function __construct(CartData $cartData)
{
$this->cartData = $cartData;
}
public function removeItem($userId, $productId) {
$this->cartData->removeItem($userId, $productId);
}
}
Note that I have removed the database calls from the actual Cart class, because that would only make it hard / impossible to swap to another database engine at some point. Or perhaps you might want to introduce a complete other way of storing your data (ahum unit testing). Also note that I have used dependency injection to give the classes the objects they need to be able to perform whatever it is they are responsible for.
I have used type hinting for the class objects which are being injected, however it would have been better to type hint against an interface, because that would make it easy to swap out the classes for other classes. And I strongly suggest you use interfaces (what I wrote above is simply an example to get the idea). This also make it pretty easy to created unit tests for your code.
At every page request, you make a new database connection. You can't share a connection between requests.
There are a couple of different design patterns (best practises) for handling this. For all of them, you need a DB abstraction layer (like PDO, Doctrine DBAL or something else).
Dependency Injection (recommend)
The most used design pattern to handle this is dependency injection:
class Foo
{
/**
* #var DatabaseAbstractionLayer
*/
private $dbal;
public function __construct(DatabaseAbstractionLayer $dbal)
{
$this->dbal = $dbal;
}
public function methodThatUsesTheDbal()
{
$this->dbal->query(...);
}
}
$db = new DatabaseAbstractionLayer();
$foo = new Foo($db); // constructor injection
$bar = new Bar();
$bar->setDbal($db); // setter injection
$baz = new Baz();
$baz->dbal = $db; // property injection (almost never used)
You can use a service container to handle this easily (example with pimple):
$container = new Pimple();
$container['db'] = $container->share(function ($c) {
return new DatabaseAbstractionLayer();
});
$container['foo'] = function ($c) {
return new Foo($c['db']);
};
$foo = $container['foo']->methodThatUsesDbal();
Singleton
class DatabaseAbstractionLayer
{
private static $_instance;
// ...
private function __construct()
{
// ...
}
// ...
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new static();
}
return self::$_instance;
}
}
class Foo
{
public function methodThatUsesDbal()
{
$db = DatabaseAbstractionLayer::getInstance();
// ...
}
}
Registery
Registery::set('db', new DatabaseAbstractionLayer());
class Foo
{
public function methodThatUsesRegistery()
{
Registery::get('db');
// ...
}
}

use an object previously declared in an other class

This is my general php page:
<?php
require_once('includes.php');
require_once('cms.class.php');
.....
rest of the page
?>
in includes.php an pro object called $db is initiated which I want to use in the class specified in the cms.class.php
includes.php:
$db = new PDO('mysql:host=localhost;dbname=xxxxx','xxxxx','xxxxxx');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
How can I use this database object in my classes without having multiple places where my credentials are stored?
You need want a dependency manager or a bootstrapper or whatever you want to call it.
class Dependency_Manager {
private $db;
public function __construct($settings) {
$this->db = new PDO('mysql:host=localhost;dbname=' . settings["dbname"],settings["username"],$setings["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
public function getDB() {
return $db;
}
}
class CMS {
public function __construct(PDO $db) {
/* .. */
}
}
$setting = array(/* etc */);
$dm = new Dependency_Manager($settings);
$cms = new CMS($dm->getDB());
This approach scales very well and can handle any dependecy. It also aims to put all the settings in one place so you don't have configuration settings littered everywhere. The $dm is the only one who knows the settings, if you need to construct something based on the settings, put it in the $dm.
There are 2 ways that you could go about this.
The first way, injection, is growing in popularity. Injection means you would supply $db to your class. You could do something like this.
Injection:
class CMS_class {
protected static $db;
public function __construct($db) {
if ( ! isset(self::$db))
self::$db = $db;
}
public function __get($name) {
if ($name === 'db')
return self::$db;
}
}
Now when you construct the CMS class you pass it the $db variable which is accessible via ->db, but there is only one instance.
The second method would be to call it globally in every function you use it.
Global:
class CMS_class {
function hello_world() {
global $db;
var_dump($db);
}
}
This way is losing popularity because globals are generally frowned upon and you will have to declare it in every function that you need $db.
There are other good answers out there that relate to your question.
How can I use "Dependency Injection" in simple php functions, and should I bother?

PHP: Classes to use functions from each other?

I've been into this problem for a while already, and have asked some questions about it here Stackoverflow. I've got some advice, but I just can't understand it. Could someone provide me an example of classes working smoothly together.
I have 3 (maybe more) classes:
mysql
user
alerts
As I said, could someone provide an example, so these classes could use functions from each other class, e.g. user could use mysql's functions. I'm asking for an simple example, for learning-purposes.
And please, no google-suggestions or links to other questions. I've tried to search this for a while already. No success, though.
Martti Laine
I really recommend you read about classes first - http://php.net/manual/en/language.oop5.php because these are basic concepts if you don't understand a single code example won't help you much.
class Mysql {
// Public function accessible from everywhere, with class instance
public function hello() {
echo '<br>Mysql says Hello';
}
// Static function accesible from everywhere, without class instance
static function bye() {
echo '<br>Mysql says Bye';
}
}
class User {
// Public function accessible from everywhere, with class instance
public function hello() {
$mysql = new Mysql();
$mysql->hello();
Mysql::bye();
}
}
class Alert {
// Static function accesible from everywhere, without class instance
static function hello() {
$user = new User();
$user->hello();
}
}
$user = new User();
$user->hello();
Mysql::bye();
Alert::hello();
It's hard to understand exactly what you mean when you say "working smoothly together". Classes can be used together in a myriad of ways. If they couldn't be then object oriented programming wouldn't be much good.
Here is a simple example:
class mysql {
private $alert;
public function __construct(alerts $alert) {
$this->alert = $alert;
}
public function dosomething() {
if(/* something went wrong */ ) {
$this->alert->showAlert();
}
}
}
There are two way you can do it.
1st: Use static methods
<?php
class mysql_database
{
public static function query($q)
{
return mysql_query($q);
}
}
class user
{
public function get()
{
//calling static method from another class
return mysql_database::query("SELECT * FROM users");
}
}
?>
2nd: Give objects instances as a parameters to other objects methods
<?php
class mysql_database
{
public function query($q)
{
return mysql_query($q);
}
}
class user
{
public function get($DB)
{
//calling method using given instance
return $DB->query("SELECT * FROM users");
}
}
$DB = new mysql_database();
$user = new user();
$user->get($DB);
?>
You can smoothly :
Instanciate an object from one class within another one
Pass an object instance into another one : this is called dependency injection
Use static function calls
In all big PHP apps, I see a mix of all 3.
Their use depends of the whole design of application, usage, refactoring an testability needs, etc.
Classes should be working together to achieve a desired result. If you are looking for dependency injection in particular or other methods they are explained in most OOP literature.
But if let's say your Mysql Class exposes a number of functions that will be used by your user class you could inject an instance of the Mysql Class into your user class upon instanstiation:
class User {
private $db = null;
public function __construct($mysql) {
$this->db = $mysql
}
public function getUserName($userID){
$sql = "SQL_QUERY";
$result = $this->db->ExecuteQuery($sql);
}
}
Please make sure you read the CONS of Dependency Injection and understand WHY this method is preferred over others. If you which to change your Mysql Class to DBClass and not break your existing code you will have to implement the same methods. Of cousre this can get more "complicated" so a careful Design might be needed (your classes might have to extend abstract classes or implement interfaces)....
I suggest you spend some time on the literature and study some patterns to get an overall idea..it's enough to get you started (a good starting point in my opinion)
following is another example.
class MySql
{
private function query($q)
{
return mysql_query($q);
}
public function checkCredentials($user, $pass)
{
$query = "" // add code here to check the user credentials
$result = query($query);
$outcome = <true/false>;//based on however you analyze your result
return $outcome;
}
}
class alert
{
public function generateAlert($alert)
{
//code to display your alert
}
}
class user
{
var $mysql;
var $alert;
public function __construct($mysql, $alert)
{
$this->mysql = $mysql;
$this->alert = $alert;
}
public function checkLogin($user, $pass)
{
if (!$this->mysql->checkCredentials($user, $pass))
$this->alert->generateAlert("login failed!");
}
}
There are many ways of doing object oriented design, it really depends on what the requirements for your project are. I also recommend visiting the PHP site and looking their OOP tutorials.

Categories