PHP - Help With Mysqli Singleton Class
I have a singleton class that I am revamping and need a little help with. I want to use the following syntax for my queries without having to declare a global object. Below is my current code:
Code: [Select] /** * The db database object * * @access private * @var object */ private $db; /** * MySQLi database object * * @access private * @var object */ private static $instance; /** * Current result set * * @access private * @var object */ private $result; /** * The last result (processed) * * @access private * @var array */ private $last_result; /** * The number of rows from last result * * @access private * @var int */ private $row_count; /** * Last error * * @access private * @var string */ private $last_error; /** * PHP5 Constructor * * Making this function 'private' blocks this class from being directly created. * * @access private */ private function __construct() { } /** * Creates and references the db object. * * @access public * @return object MySQLi database object */ public static function instance() { if ( !self::$instance ) self::$instance = new db(); return self::$instance; } /** * Connect to the MySQL database. * * @param string $host MySQL hostname * @param string $user MySQL username * @param string $password MySQL password * @param string $name MySQL database name * @return bool True if successful, false on error. */ public function connection($host, $user, $password, $name) { // Connect to the database $this->db = new mysqli($host, $user, $password, $name); // Check connection if ( mysqli_connect_errno() ) { $this->last_error = mysqli_connect_error(); return false; } return true; } public function query($sql) { $this->result = $this->db->query($sql); return $this->result; } So then, what would I need to change in my class so that I will not have to declare a global variable for other classes and functions to use like db::query->();? Thanks in advance for your help. Similar TutorialsHi, i made a singleton class to make connecting to the db easyer.
I got some questions.
1: is this the right way i wrote this class?
2: how can i easy implement mysqli prepare in this class?
I've looked everywhere but prepared staments need more lines of code to make it work and i don't know how to implement that in the singleton class.
<?php require_once(dirname(dirname(__FILE__)) . "/config.php"); class Database { public static $instance; private $mysqli, $query, $results, $count = 0; public static function getInstance() { if (!self::$instance) { self::$instance = new Database(); } return self::$instance; } public function __construct() { $this->mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE); if ($this->mysqli->connect_error) { die($this->mysqli->connect_error); } } public function query($sql) { if ($this->query = $this->mysqli->query($sql)) { while ($row = $this->query->fetch_assoc()) { $this->results[] = $row; } $this->count = $this->query->num_rows; } return $this; } public function results() { return $this->results; } public function count() { return $this->count; } } ?>usage: <?php include('database.php'); $r = Database::getInstance()->query('SELECT * FROM users'); foreach ($r->results() as $row) { echo $row['name'] . '</br>'; } echo $r->count(); ?> I want to create a singleton class that read multidimensional array from txt file and flatten the array retrieved. I have a function that performs a SELECT query on a MySQL database and populates the results in an array of Class. At the moment it is using PDO. Trouble is that PDO is not supported by the server the code will run on. Changing server is not an option, nor is installing PDO.
I have tried splitting the function to use the PDO method if installed or MySQLi if not. I am struggling to get the MySQLi part working though. Can anyone help me with this?
Here is the function I have so far which basically returns nothing from the MySQLi part:
public function mysqlSelectToClass($query, $className, $args = NULL) { include (dirname(__FILE__) . "/../config.php"); if (class_exists('PDO')) { $db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_user, $db_pass); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbQuery = $db->prepare($query); if (isset($args)) { foreach ($args as $arg) { $dbQuery->bindParam(array_values($arg)[0], array_values($arg)[0], PDO::PARAM_STR); } } $dbQuery->execute(); return $dbQuery->fetchAll(PDO::FETCH_CLASS, $className); } else { $db = mysqli_connect($db_host, $db_user, $db_pass, $db_name); $dbQuery = $db->prepare($query); if (isset($args)) { // Type is a string of parameter types e.g. "is" $type = array_values($args)[0]; // Params is an array of parameters e.g. array(1, 'value') $params = array_values($args)[1]; call_user_func_array('mysqli_stmt_bind_param', array_merge(array($dbQuery, $type), $this->byrefValues($params))); $result = mysqli_stmt_execute($dbQuery); mysqli_close($db); } elseif ($dbResult = mysqli_query($db, $query)) { $result = mysqli_fetch_object($dbResult, $className); mysqli_close($db); } return $result; } }the byrefValues function is simply swapping a value array to a reference array and seems to be working fine. I can paste that too if required. Thanks Jay Edited by jay20aiii, 24 September 2014 - 12:41 PM. Hey Guys, So I am working on implementing zip codes to my database. I found a zip code calculator script, and I am forced to pass the database connection to the class. Although, I realize I use a mysqli connection and the zipcodes class uses mysql... Appreciate if anyone could assist me in solving my issue. THANKS! ERRORS... Quote Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/bleeping/public_html/gregstechservices.com/gregphp/ZipCodesRange.class.php on line 287 Warning: mysql_errno(): supplied argument is not a valid MySQL-Link resource in /home/bleeping/public_html/gregstechservices.com/gregphp/ZipCodesRange.class.php on line 289 Warning: mysql_error(): supplied argument is not a valid MySQL-Link resource in /home/bleeping/public_html/gregstechservices.com/gregphp/ZipCodesRange.class.php on line 289 MySql Error #: zip.php <?php require_once("class/mysql_connect.php"); $mysql = New MySQL(); require_once("ZipCodesRange.class.php"); //initialization, pass in DB connection, from zip code, distance in miles. $zip = new ZipCodesRange($mysql,'98303',50); //configuration $zip->setTableName('zipcodes'); //optional, default is zips. $zip->setZipColumn('ZipCode'); //optional, default is zip. $zip->setLonColumn('Longitude'); //optional, default is lon. $zip->setLatColumn('Latitude'); //optional, default is lat. //do the work $zip->setZipCodesInRange(); //call to initialize zip array //zip code output, other processing can be done from this array. $zipArray = $zip->getZipCodesInRange(); echo '<pre>'; print_r($zipArray); echo '</pre>'; ?> mysql_connect.php <?php require_once ("includes/constants.php"); class MySQL { private $conn; /** * MySQL::__construct() * * @return */ function __construct() { $this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME) or die("Problem connecting to database"); $dbc = $this->conn; } /* * Query the database * Example: $result = $mysql->query($q); */ /** * MySQL::query() * * @param mixed $q * @return */ function query($q) { return $this->conn->query($q); } ...CONTINUED ZipCodesRange.class.php <?php /** * Class to find zip codes within an approximate * distance of another zip code. This can be useful * when trying to find retailers within a certain * number of miles to a customer. * * This class makes some assumptions that I consider * pretty safe. First it assumes there is a database * that houses all of the zip code information. * Secondly it assumes there is a way to validate a * zip code for a given country. It makes one bad * assumption and that is that the world is flat. See * comments below for an explanation. * * @author Scott Mattocks * @created 2004-05-03 * @updated 2004-05-14 * @updated 2006-05-22 - MySQL Conversion by Allan Bogh * - Added precisionDistance() function to make calculations * more accurate (within 2 miles). * - Modified class initialization to make custom database settings * more effective. * New initialization steps: * $zip = new ZipCodesRange($appconf['dbconnection'],'98303',50); * $zip->setTableName('zip_codes'); //optional * $zip->setZipColumn('zip'); //optional * $zip->setLonColumn('longitude'); //optional * $zip->setLatColumn('latitude'); //optional * $zip->setZipCodesInRange(); //call to initialize zip array * echo '<pre>'; * print_r($zip->getZipCodesInRange()); * echo '</pre>'; */ class ZipCodesRange { /** * The conversion factor to go from miles to degrees. * @var float */ var $milesToDegrees = .01445; /** * The zipcode we are starting from. * @var string */ var $zipCode; /** * The maximum distance in miles to return results for. * @var float */ var $range; /** * The country the zip code is in. * @var string Two character ISO code. */ var $country; /** * The result of our search. * array(zip1 => distance, zip2 =>distance,...) * @var array */ var $zipCodes = array (); /** * The database table to look for zipcodes in. * @var string */ var $dbTable = 'zips'; /** * The name of the column containing the zip code. * @var string */ var $dbZip = 'zip'; /** * The name of the column containing the longitude. * @var string */ var $dbLon = 'lon'; /** * The name of the column containing the latitude. * @var string */ var $dbLat = 'lat'; var $db; /** * Constructor. Calls initialization method. * * @access private * @param resource $db The link identifier for the database. * @param string $zipCode * @param float $range * @param string $country Optional. Defaults to US. * @return object */ function ZipCodesRange($db, $zipCode, $range, $country = 'US') { $this->_initialize($db, $zipCode, $range, $country); } /** * Initialization method. * Checks data and sets member variables. * * @access private * @param resource $db The link identifier for the database. * @param string $zipCode * @param float $range * @param string $country Optional. Defaults to US. * @return boolean */ function _initialize($db, $zipCode, $range, $country) { //set up the database connection $this->db = $db; // Check the country. if ($this->validateCountry($country)) { $this->country = $country; } else { trigger_error('Invalid country: ' . $country); return FALSE; } // Check the zipcode. if ($this->validateZipCode($zipCode, $country)) { $this->zipCode = $zipCode; } else { trigger_error('Invalid zip code: ' . $zipCode); return FALSE; } // We don't need a special method to check the range. if (is_numeric($range) && $range >= 0) { $this->range = $range; } else { trigger_error('Invalid range: ' . $range); return FALSE; } // Set up the zip codes. //return $this->setZipCodesInRange(); } /** * Get all of the zip codes from the database. * Currently this method is called on construction but * it doesn't have to be. * * @access public * @return boolean */ function setZipCodesInRange() { // First check that everything is set. if (!isset($this->zipCode) || !isset($this->range) || !isset($this->country)) { trigger_error('Cannot get zip codes. Class not initialized properly.'); return FALSE; } // Get the max longitude and latitude of the starting point. $maxCoords = $this->getRangeBox(); // The query. $query = 'SELECT ' . $this->dbZip . ', ' . $this->dbLat . ', '; $query.= $this->dbLon . ' '; $query.= 'FROM ' . $this->dbTable . ' '; $query.= ' WHERE '; $query.= ' (' . $this->dbLat . ' <= ' . $maxCoords['max_lat'] . ' '; $query.= ' AND '; $query.= ' ' . $this->dbLat . ' >= ' . $maxCoords['min_lat'] . ') '; $query.= ' AND '; $query.= ' (' . $this->dbLon . ' <= ' . $maxCoords['max_lon'] . ' '; $query.= ' AND '; $query.= ' ' . $this->dbLon . ' >= ' . $maxCoords['min_lon'] . ') '; // Query the database. $qry = mysql_query($query,$this->db); // Check for errors. if (!$qry) { trigger_error('MySQL Error #'.mysql_errno($this->db).': '.mysql_error($this->db), E_USER_ERROR); } // Process each row. while ($result = mysql_fetch_array($qry)) { // Get the distance form the origin (imperfect see below). $distance = $this->precisionDistance($result[$this->dbLat], $result[$this->dbLon]); // Double check that the distance is within the range. if ($distance < $this->range) { // Add the zip to the array $this->zipCodes[$result[$this->dbZip]] = $distance; } } return TRUE; } /** * Return the array of results. * * @access public * @param none * @return &array */ function &getZipCodesInRange() { return $this->zipCodes; } /** * Calculate the distance from the coordinates are from the * origin zip code. * * The method is quite imperfect. It assumes as flat Earth. * The values are quite accurate (depending on the conversion * factor used) for zip codes close to the equator. I found * some crazy formula for calulating distance on a sphere * but I am not good enough at calculus to convert that into * working code. * * @access public * @param float $lat The latitude you want to know the distance to. * @param float $lon The longitude you want to know the distance to. * @param float $zip The zip code you want to know the distance from. * @param int $percision The number of decimals places in the distance. * @return float The distance from the zip code to the coordinates. */ function calculateDistance($lat, $lon, $zip = NULL, $percision = 2) { // Check the zip first. if (!isset ($zip)) { // Make it default to the origin zip code. // Could be used to calculate distances from other points. $zip = $this->zipCode; } // Get the coordinates of our starting zip code. list ($starting_lon, $starting_lat) = $this->getLonLat($zip); // Get the difference in miles for both coordinates. $diffLonMiles = ($starting_lon - $lon) / $this->milesToDegrees; $diffLatMiles = ($starting_lat - $lat) / $this->milesToDegrees; // Calculate the distance between two points. $distance = sqrt(($diffLonMiles * $diffLonMiles) + ($diffLatMiles * $diffLatMiles)); // Return the distance rounded to the defined percision. return round($distance, $percision); } /** * See the report for calculateDistance function. */ function precisionDistance($lat, $lon, $zip = NULL, $precision = 2){ $earthsradius = 3963.19; // Check the zip first. if (!isset ($zip)) { // Make it default to the origin zip code. // Could be used to calculate distances from other points. $zip = $this->zipCode; } // Get the coordinates of our starting zip code. list ($starting_lon, $starting_lat) = $this->getLonLat($zip); $pi = pi(); $c = sin($starting_lat/(180/$pi)) * sin($lat/(180/$pi)) + cos($starting_lat/(180/$pi)) * cos($lat/(180/$pi)) * cos($lon/(180/$pi) - $starting_lon/(180/$pi)); $distance = $earthsradius * acos($c); return round($distance,$precision); } /** * Get the longitude and latitude for a single zip code. * * @access public * @param string $zip The zipcode to get the coordinates for. * @return array Numerically index with longitude first. */ function getLonLat($zip) { // Get the longitude and latitude for the zip code. $query = 'SELECT ' . $this->dbLon . ', ' . $this->dbLat . ' '; $query.= 'FROM ' . $this->dbTable . ' '; $query.= 'WHERE ' . $this->dbZip . ' = \'' . addslashes($zip) . '\' '; $qry = mysql_query($query,$this->db); if(!$qry){ echo "MySql Error #".mysql_errno($this->db).': '.mysql_error($this->db).'<br>'; die; } return mysql_fetch_array($qry); } /** * Check to see if the country is valid. * * Not implemented in any useful manner. * * @access public * @param string $country The country to check. * @return boolean */ function validateCountry($country) { return (strlen($country) == 2); } /** * Check to see if a zip code is valid. * * Not implemented in any useful manner. * * @access public * @param string $zip The code to validate. * @param string $country The country the zip code is in. * @return boolean */ function validateZipCode($zip, $country = NULL) { // Set the country if we need to. if (!isset($country)) { $country = $this->country; } // There should be a way to check the zip code for every // acceptabe country. return TRUE; } /** * Get the maximum and minimum longitude and latitude values * that our zip codes can be in. * * Not all zipcodes in this box will be with in the range. * The closest edge of this box is exactly range miles away * from the origin but the corners are sqrt(2(range^2)) miles * away. That is why we have to double check the ranges. * * @access public * @param none * @return &array The edges of the box. */ function &getRangeBox() { // Calculate the degree range using the mile range $degrees = $this->range * $this->milesToDegrees; // Get the coords for our starting zip code. list($starting_lon, $starting_lat) = $this->getLonLat($this->zipCode); // Set up an array to return. $ret_array = array (); // Lat/Lon ranges $ret_array['max_lat'] = $starting_lat + $degrees; $ret_array['max_lon'] = $starting_lon + $degrees; $ret_array['min_lat'] = $starting_lat - $degrees; $ret_array['min_lon'] = $starting_lon - $degrees; return $ret_array; } /** * Allow users to set the name of the database table holding * the information. * * @access public * @param string $table The name of the db table. * @return void */ function setTableName($table) { $this->dbTable = $table; } /** * Allow users to set the name of the column holding the * latitude value. * * @access public * @param string $lat The name of the column. * @return void */ function setLatColumn($lat) { $this->dbLat = $lat; } /** * Allow users to set the name of the column holding the * longitude value. * * @access public * @param string $lon The name of the column. * @return void */ function setLonColumn($lon) { $this->dbLon = $lon; } /** * Allow users to set the name of the column holding the * zip code value. * * @access public * @param string $zips The name of the column. * @return void */ function setZipColumn($zip) { $this->dbZip = $zip; } /** * Set a new origin and re-get the data. * * @access public * @param string $zip The new origin. * @return void */ function setNewOrigin($zip) { if ($this->validateZipCode($zip)) { $this->zipCode = $zip; $this->setZipCodesInRange(); } } /** * Set a new range and re-get the data. * * @access public * @param float $range The new range. * @return void */ function setNewRange($range) { if (is_numeric($range)) { $this->range = $range; $this->setZipCodesInRange(); } } /** * Set a new country but don't re-get the data. * * It isn't any good to check a zip code in two * countries cause the rules for zip codes vary from * country to country. * * @access public * @param string $country The new country. * @return void */ function setNewCountry($coutry) { if ($this->validateCountry($country)) { $this->country = $country; } } /** * Allow users to set the converstion ratio. * Hopefully you are changing the percision * and not setting a bad value. * * @access public * @param float $rate The new value. * @return void */ function setConversionRate($rate) { if (is_numeric($rate)) { $this->milesToDegrees = $rate; } } } /* Debugging lines $zcr = new ZipCodesRange(10965, 10); print_r($zcr); */ ?> Hi,
I am trying to connect to a database using mysqli from a web developing software package called Sellerdeck.
This software is purely windows based, it has PHP configured to a certain extent it seems.
I ran the phpinfo(); command and can't find anything to do with MYSQL in the settings of the version.
So i tried to download the php_mysql.dll and libmysql.dll files, I have referenced them in the php.ini file by using
extension_dir="./"
extension=php_mysql.dll
extension=libmysql.dll
(Also best to mention that " extension_dir="./" " was the only line of text in the php.ini file by default)
This didn't seem to make a difference at all, still get the same error.
Is there anything I can try to do? I really can't understand it as php 5 comes with mysql built in, but it seems that Sellerdeck have stripped that usability from the php version!
Any advice appreciated
Edited by engy123, 30 January 2015 - 03:58 AM. I don't know why it won't work.. as the topic titles says that I am trying to pass a mysqli object to a property in another class but it keeps me getting an error.
here's the code for the mysqli object that i want to pass to another class
class ConnectMe2Db { public $dbname = 'somedatabase'; public $dbuname = 'root'; public $dbpass = ''; public $dbhost = 'localhost'; function __construct() { $mysqli = new mysqli($this->dbhost,$this->dbuname,$this->dbpass,$this->dbname) or die ('ERROR: '.$mysqli->connect_errno); return $mysqli; } # OTHER CODES... }and here is the class that i want the Mysqli object to pass to: class DatabaseUsers { private $dbconnection; function __construct() { $this->dbconnection = new ConnectMe2Db();#mysqli object will be passed to this attribute '$dbconnection' } public function session($username, $password) { $UserName = mysqli_real_escape_string($this->dbconnection,$username); $Password = mysqli_real_escape_string($this->dbconnection,md5($password)); $querry = "SELECT * FROM trakingsystem.login WHERE username='$username' and password='$password'"; $result = mysqli_query($this->dbconnection,$querry) or die (mysqli_error($this->dbconnection)); $count = mysqli_num_rows($result); $row = mysqli_fetch_array($result); if ($count > 0) { #some code here } } #some other code here }and this outputs 4 errors: #outputs 2 of these: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqliand some mysqli_query() expects parameter 1 to be mysqli mysqli_error() expects parameter 1 to be mysqliis there something wrong with the logic that I've made? please help thanks I've searched all over for the past few days trying to figure out what I'm doing wrong. Basically what I'm trying to do is create a prepared statement inside my User class. I can connect to the database, but my query does not execute as expected. Here's the code for my User class Code: [Select] <?php include '../includes/Constants.php'; ?> <?php /** * Description of User * * @author Eric Evas */ class User { var $id, $fname, $lname, $email, $username, $password, $conf_pass; protected static $db_conn; //declare variables public function __construct() { $host = DB_HOST; $user = DB_USER; $pass = DB_PASS; $db = DB_NAME; //Connect to database $this->db_conn = new mysqli($host, $user, $pass, $db); //Check database connection if ($this->db_conn->connect_error) { echo 'Connection Fail: ' . mysqli_connect_error(); } else { echo 'Connected'; } } function regUser($fname, $lname, $email, $username, $password, $conf_pass) { if ($stmt = $this->db_conn->prepare("INSERT INTO USERS (user_fname,user_lname, user_email,username,user_pass) VALUES (?,?,?,?,?)")) { $stmt->bind_param('sssss', $this->fname, $this->lname, $this->email, $this->username, $this->password); $stmt->execute(); $stmt->store_result(); $stmt->close(); } } } ?> And here's the file that I created to instantiate an instance of the user class. Code: [Select] <?php include_once 'User.php'; ?> <?php //Creating new User Object $newUser = new User(); $newUser->fname = $_POST['fname']; $newUser->lname = $_POST['lname']; $newUser->email = $_POST['email']; $newUser->username = $_POST['username']; $newUser->password = $_POST['password']; $newUser->conf_pass = $_POST['conf_pass']; $newUser->regUser($newUser->fname, $newUser->lname, $newUser->email, $newUser->username, $newUser->password, $newUser->conf_pass); ?> And lastly heres the form that I want to get info from the user to insert into the database Code: [Select] <html> <head> <title></title> <link href="stylesheets/styles.css" rel="stylesheet" type="text/css"/> </head> <body> <form action = "Resources/testClass.php" method="post" enctype="multipart/form-data"> <label>First Name: </label> <input type="text" name="fname" id="fname" size="25" maxlength="25"/> <label>Last Name: </label> <input type="text" name="lname" id="lname" size="25" maxlength="25"/> <label>Email: </label> <input type="text" name="email" id="email" size="25" maxlength="40"/> <label>Username: </label> <input type="text" name="username" id="username" size="25" maxlength="32"/> <label>Password: </label> <input type="password" name="password" id="password" size="25" maxlength="32"/> <label>Re-enter Password: </label> <input type="password" name="conf_pass" id="conf_pass" size="25" maxlength="32"/> <br /><br /> <input type="submit" name="submit" id="submit" value="Register"/> <input type="reset" name="reset" id="reset" value="Reset"/> </form> </body> </html> I closed everything down last night and it was all fine, website was working as normal etc, but I've turned on the Xxamp server today and I am getting this error. Seems very random as nothing has changed since it was last on? Does anyone know how to sort this out and why I'm now getting this error? Thanks! (example I looked at: http://develturk.com/tags/selfinstance/) I've looked into the singleton pattern and a few examples. I've understood most of its concept, but I still have a few things puzzling me. I noticed that you're not supposed to allow cloning (obviously) or the construction method as it shows in an example: //this object can not copy //except the getInstance() method. private function __clone() {} //prevent directly access //we want acces this only from getInstance method. private function __construct(){} Do I also have to do this for child classes, or just the parent class? I have a questions regarding Singleton Pattern in this video: http://www.youtube.com/watch?v=-uLbG7nJCJw&feature=plcp&context=C49f92beVDvjVQa1PpcFMxdGEHDoxYON2LEGpH0krK5UV1HfoVHGM= Using the singleton pattern, isn't possible to have methods that aren't static? In this video it shows nothing but static methods. Also, after creating the class object like so: $database = Database:Connect(); How would I go about using normal functions with that object? Say I had a query function. I can't do this: $database->query(); So what would I do? :/ - Thanks for any help regarding this. OK, so I'm trying to create a central db class for data validation, etc. I'm starting off with the data. this code works for me, I just want to be sure that I'm not missing anything. Will dbData be accessible globally? Code: [Select] class dbData{ function regex_key_data($reg){ $z = '/[a-z\s\'{1}]*/'; $d= array( 'domain'=>'/^[a-z0-9-.]+\.[a-z0-9]{2,4}$/i', 'email'=>'/^[a-z0-9._-]+@[a-z0-9._-]+\.[a-z]+$/i', 'GUID'=>'/[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}/', 'html'=>'*htmlentities', 'int'=>'[0-9]', 'string'=>'*mysql_real_escape_string', 'fname'=>$z, 'lname'=>$z ); return $d[$reg]; } function test($reg,$val){ $z = preg_match(dbData::regex_key_data($reg),$val ,$dom); return ($z?$dom[0]:false); } } function clean_it($v,$type = 'none'){ $v = urldecode($v); if(!empty($v)){ switch($type){ case 'domain': return dbData::test('domain',$v); break; case 'email': preg_match('/^[a-z0-9._-]+@[a-z0-9._-]+\.[a-z]+$/i', $v,$email); if(empty($email[0])){return 'empty';} else{return mysql_real_escape_string($email[0]);} break; case 'GUID': return mysql_real_escape_string($v); break; case 'html': return mysql_real_escape_string(htmlentities($v)); break; case 'int': if(is_numeric($v)){return $v;} break; case 'string': return mysql_real_escape_string($v); break; } } else{ switch($type){ case 'domain': case 'none': case 'string': case 'email': case 'GUID': case 'html': return 'empty'; break; case 'int': return 0; break; } } } $br = '<br/>'; echo dbData::test('GUID','ASDFASDF-ASDF-ASDF-ASDF-ASDFASDFASDF').$br; echo dbData::test('email','asdf@asdf.asd').$br; echo clean_it('asdfsdf.com','domain'); I'm looking for some clarification here from different viewpoints to understand real world applications. In a previous thread, I suggested to someone that they read up on singleton methods to restrict class duplication (oops!), I was quickly (and rightfully) shot down. I did this after having read through blog posts that also suggested singleton design to stop multiple MySQL connections. At the time I didn't consider that could be useful to some people.. fair enough. Thankfully I don't use singleton methods within my own code, but I do use static methods for most things. Reading through numerous blog posts, tutorials, etc.., it seems like static methods can also be considered anti-design and is something to avoid. So now it seems I'm at a point where I need to rewrite my existing framework & CMS, probably using dependency injection within my classes. I understand how this works, and why it makes sense. What I'm struggling with is understanding how to use dependency injection within a (personal) CMS application. For example - I have a config.ini file I have a class that reads the .ini file, stores the variables, and provides me methods to access them I have a content class that selects the relevant page/component from the DB (db & config dependency), then displays it via my template engine. Within the included view files I call component classes (articles, contact, etc..), each of these require a connection to the DB, which has a config dependency. Here's some code to explain it better - index.php <?php $settings = '/config/config.ini'; $config = new Config($settings); $db = new Database($config); $content = new Content( $db ); // Config may also be passed for content config - keeping it simple for example print $content->loadPage($_GET['page']); // This would now include the code below ?>Let's say that this then loads the article index (through $content->loadPage()). The view would look something like this - article_index.php <?php // Duplicated code $settings = '/config/config.ini'; $config = new Config($settings); $db = new Database($config); // Article code $articles = new Articles_Model($db); return $articles->getArticles(0,15); ?>Now my problem is that I'm duplicating the config and db class calls for no reason. Is the sollution to store these within a registry class? But then I'm creating globals, which again seems anti-design. Or is the problem how I load the active page? Any insights would be much appreciated. I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks Hi Can you call Class A's methods or properties from Class B's methods? Thanks. Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. Hi people! class FirstOne{ public function FunctionOne($FirstInput){ //do stuff and output value return $value1; } } Then:- class SecondOne{ public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } } What I want to know is this, if I want to use FunctionOne() in Class SecondOne do I do it like this:- (Assume as I have instantiated the first class using $Test = new FirstOne(); ) class SecondOne{ function SecondedFunction(){ global $Test; return $Test->FunctionOne(); } public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } public function FunctionThree(){ //some code here $this->Test->SecondedFunction();<--I think as I can omit the $this-> reference } } My point is: Do I have to do it this way or is there way of having this done through __construct() that would negate the need for a third party function? I have a version working, I just think that it is a little convoluted in the way as I have done it, so I thought I would ask you guys. Any help/advice is appreciated. Cheers Rw I have two classes: ## Admin.php <?php class Admin { public function __construct() { include("Config.php"); } /** * deletes a client * @returns true or false */ function deleteClient($id) { return mysql_query("DELETE FROM usernames WHERE id = '$id'"); } } ?> ## Projects.php <?php class Projects { public function __construct() { include("Config.php"); $this->admin = $admin; $this->dataFolder = $dataFolder; } /** * Deletes a project * @returns true or false */ function deleteProject($id) { $root = $_SERVER['DOCUMENT_ROOT']; $theDir = $root . $this->dataFolder; $sql = mysql_query("SELECT * FROM projectData WHERE proj_id = '$id'"); while ($row = mysql_fetch_array($sql)) { $mainFile = $row['path']; $thumb = $row['thumbnail']; if ($thumb != 'null') { unlink($theDir . "/" . substr($thumb,13)); } unlink($theDir . "/" . substr($mainFile,13)); } $delete = mysql_query("DELETE FROM projectData WHERE proj_id = '$id'"); $getDir = mysql_query("SELECT proj_path FROM projects WHERE id = '$id'"); $res = mysql_fetch_array($getDir); rmdir($theDir . "/" . $res['proj_path']); return mysql_query("DELETE FROM projects WHERE id = '$id'"); } } ?> How can I call deleteProject() from within Admin.php? |