A Snippet from my latest project

Status
Not open for further replies.

litewarez

Active Member
1,367
2008
1
0
Ok so this is just an insider to a new project im working on

now this project is a professional website that is built on PHP 5.1+ and will not be released under any licence and im not going to be telling you what the site is etc because i like to keep my professional work seperate to my fun work.. aka the scene so here take a look at it

mysql.class.php

PHP:
<?php 

class MySql{
	var $settings = array();
	var $handlers = array();
	var $errors = array();
	var $query_Data = array();
	
	function __construct($host,$user,$pass,$db){
		$this->settings['credentials']['host'] = $host;
		$this->settings['credentials']['user'] = $user;
		$this->settings['credentials']['pass'] = $pass;
		$this->settings['credentials']['data'] = $db;
		
		//Start the connection
		$this->__Connect();
		$this->__Assoc_Database();
		
		//Some Charactor Setting
		mysql_query("SET NAMES 'utf8'",$this->handlers['connect']);
		mysql_query("SET CHARASET SET 'utf8'",$this->handlers['connect']);
	}
	
	public function query($query){
		$resource = mysql_query($query);
		
		if($resource){
			if(is_resource($resource)){
				//Set some vars
				$i = 0;
				$data = array();
				
				//Loop the results 
				while($row = mysql_fetch_assoc($resource)){
					$this->query_Data[$i] = $row;
					$i++; //Post ++
				}
				mysql_free_result($resource);
				
				$query = new stdClass();
				$query->row = (isset($this->query_Data[0]) ? $this->query_Data : array());
				$query->rows = $this->query_Data;
				$query->numrows = $i;
				
				unset($this->query_Data);
				return $query;
			}
		}else{
			 $this->__Error(__FILE__,__CLASS__,__METHOD__,__LINE__,mysql_error());
		}
	}
	
	private function __Connect(){
		$this->handlers['connect'] = mysql_connect(
			$this->settings['credentials']['host'],
			$this->settings['credentials']['user'],
			$this->settings['credentials']['pass']) or
				$this->__Error(__FILE__,__CLASS__,__METHOD__,__LINE__,mysql_error());
	}
	
	private function __Assoc_Database(){
		$this->handlers['database'] = mysql_select_db(
			$this->settings['credentials']['data']) or
				$this->__Error(__FILE__,__CLASS__,__METHOD__,__LINE__,mysql_error());
	}
	
	private function __Error($file,$class,$funtion,$line,$error){
		die(
			sprintf("<pre class='error_php_internal'>There was an error\rFILE: %s\rCLASS: %s\rMETHOD: %s\rLINE: %d\rERROR: %s</pre>",
					$file,
					$class,
					$function,
					$line,
					$error)
		);
	}
	public function hello(){
		echo 'hello';
	}
	
	function __destruct(){
		mysql_close($this->handlers['connect']);
		unset(
			$this->settings,
			$this->handlers,
			$this->errors,
			$this->query_Data
		);
	}
}
?>

Heres my Registry where all my Objects are help and passed threw out other classes for ease of use

PHP:
<?php 
//used for holding objects on one array() ....
final class Registry{
	static private $data = array();
	
	static public function get($key){
		return (isset(self::$data[$key]) ?  self::$data[$key] : NULL);
	}
	
	static public function set($key,$value){
		self::$data[$key] = $value;
	}
	
	static function has($key){
		return isset(self::$data[$key]);
	}
}
?>

and heres the example of how the index file looks but not showing all the source :P

PHP:
<?php

//Include Main Config
include 'config.php';

//Include Startup
include $settings['dir']['includes'] . 'startup.php';

//Sessions
Registry::set('sessions',new Sessions);

//Config
$Config = new Config;
Registry::set('config',$Config);

//Mysql
$MySql = new MySql($settings['mysql']['host'],$settings['mysql']['user'],$settings['mysql']['pass'],$settings['mysql']['data']);
Registry::set('mysql',$MySql);

//Settings (keep uppercase because it will overide the config file);
$Settings = $MySql->query('SELECT * FROM settings');
foreach($Settings->rows as $row){$Config->set($row['key'], $row['value']);}

$Templater = new Templater;
Registry::set('Templater',$Templater);
?>

now if your thinking why dont i show you this in my tutorials is because no one on this site is ready for this so to speak

but enjoy looking at my source and comment on what you think of my OOP :P
 
19 comments
The DBAL (Database class) is quite nice, howeaver I would change

Code:
[COLOR=#000000][COLOR=#0000bb]mysql_query[/COLOR][COLOR=#007700]([/COLOR][COLOR=#dd0000]"SET NAMES 'utf8'"[/COLOR][COLOR=#007700],[/COLOR][COLOR=#0000bb]$this[/COLOR][COLOR=#007700]->[/COLOR][COLOR=#0000bb]handlers[/COLOR][COLOR=#007700][[/COLOR][COLOR=#dd0000]'connect'[/COLOR][COLOR=#007700]]); 
        [/COLOR][COLOR=#0000bb]mysql_query[/COLOR][COLOR=#007700]([/COLOR][COLOR=#dd0000]"SET CHARASET SET 'utf8'"[/COLOR][COLOR=#007700],[/COLOR][COLOR=#0000bb]$this[/COLOR][COLOR=#007700]->[/COLOR][COLOR=#0000bb]handlers[/COLOR][COLOR=#007700][[/COLOR][COLOR=#dd0000]'connect'[/COLOR][COLOR=#007700]]);[/COLOR][/COLOR]
to $this->query for uniformity. Though all in all nice, perhaps have an option to change charset, then you could also check that the charset is valid in the DB engin (in this case MySQL).

OOP is good, as long as its not overused. Use it for DBAL, DOM and other things but do not use it for function storage and the likes, there is no point.

Not a fan of the way you combined mysql_query and mysql_fetch_assoc in
Code:
public function [/COLOR][COLOR=#0000bb]query[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000bb]$query[/COLOR][COLOR=#007700]){
...
[/COLOR]

 
lol yea i aggree with keeping the the query in the internal object lol the reason i dont that at first was because $this->query() was only going to be used for returning arrays but i chancged it to check to see if the handler returned a resource but as ive update the class a lil i forgot to update that section :P

the reason for combining the class and the mysql_fetch _assoc is do the to template system where i only want foreach loops and while count loops, i think this way it is easier on the template system.

thanks for the comment tho dood
 
damm...
everything.. just gone up my heads :p
lol I know only the newbish PHP :p lol
I need to learn more ;)
Anyways.. by seeing your excitement, good job litewarez :)
 
Ok the code im currently rewirting, I wrote this maybe 6 months ago but im not happy with it.

Code:
<?php
/**
* Inserts values from $arr2 after (or before) $key in $arr1
* if $key is not found, $arr2 is appended to $arr1 using array_merge()
*
* @param $arr1
*   array to insert into
* @param $key
*   key of $arr1 to insert after
* @param $arr2
*   array whose values should be inserted
* @param $before
*   insert before the given key. defaults to inserting after
* @return
*   merged array
*/
function array_insert($arr1, $key, $arr2, $before = FALSE){
  $done = FALSE;
  foreach($arr1 as $arr1_key => $arr1_val){
    if(!$before){
      $new_array[$arr1_key] = $arr1_val;
    }
    if($arr1_key == $key && !$done){
      foreach($arr2 as $arr2_key => $arr2_val){
        $new_array[$arr2_key] = $arr2_val;
      }
      $done = TRUE;
    }
    if($before){
      $new_array[$arr1_key] = $arr1_val;
    }
  }
  if(!$done){
    $new_array = array_merge($arr1, $arr2);
  }
  return $new_array;
}

class post_parse_node{
	public $tag = '';
	public $attrib = '';
	public $inner = array();
	public $parent = null;
	public $main_class;
    public $uid = false;
	
	function post_parse_node($tag,$attrib,&$parent,$uid=false){
		$this->tag = $tag;
		$this->attrib = $attrib;
		$this->parent = $parent;
        $this->uid = $uid;
		return $this;
	}
	
	function plain_text($set=false){
		if($set){
			foreach($this->inner as $i){
				$i->remove();
			}
			unset($this->inner);
			$this->inner[] = new post_parse_node('__',$set,$this);
			return true;
		}else{
            $<span class="searchlite">bbcode</span> = '';
			if($this->tag==='__'){
				return $this->attrib;
			}else{
				foreach($this->inner as $tag){
					$<span class="searchlite">bbcode</span> .= $tag->plain_text();
				}
				return $bbcode;
			}
		}
	}
	
	function <span class="searchlite">bbcode</span>(){
		if($this->tag==='__'){
			return $this->attrib;
		}else{
			$<span class="searchlite">bbcode</span> = '['.$this->tag.($this->attrib?'='.$this->attrib:'').($this->uid?':'.$this->uid:'').']';
			foreach($this->inner as $tag){
				$<span class="searchlite">bbcode</span> .= $tag-><span class="searchlite">bbcode</span>();
			}
			return $<span class="searchlite">bbcode</span>.'[/'.$this->tag.($this->uid?':'.$this->uid:'').']';
		}
	}
	
	function remove(){
		$this->main_class->remove_tag($this);
		if($this->parent instanceof post_parse_node && isset($this->parent->elements)&&count($this->parent->elements)){
			foreach($this->parent->elements as $k=>$e){
				if($e===$this){
					unset($this->parent->elements[$k]);
				}
			}
		}
		if(isset($this->elements)&&count($this->elements)){
			foreach($this->elements as &$e){
				$e->parent = $this->parent();
				if($this->parent){
					$this->parent->elements[] = $e;
				}
			}
		}
		unset($this);
	}
	
	function insert_parent($item, $attrib=''){
		$old_parent = &$this->parent;
		$t = false;
		if($old_parent instanceof post_parse_node){
			foreach($old_parent->inner as $k=>$e){
				if($e===$this){
                    die(var_dump($this->uid));
					$t = new post_parse_node($item,$attrib,$old_parent,$this->uid);
					$old_parent->inner[$k] = $t;
				}
			}
		}else{
			foreach($this->main_class->elements as $k=>$e){
				if($e===$this){
					$t = new post_parse_node($item,$attrib,$old_parent,$this->uid);
					$this->main_class->elements[$k] =  &$t;
					$this->main_class->elements[] = &$this;
				}
			}
		}
		if($t){
			$t->inner[] = &$this;
			$this->parent = &$t;
			return true;
		}
		return false;
	}
	
	function clear(){
		foreach($this->inner as $k=>&$i){
			if($i instanceof post_parse_node){
				$i->clear();
				if($this->inner[$k] instanceof post_parse_node){
					$this->inner[$k]->clear();
				}
				unset($this->inner[$k]);
				unset($i);
			}
		}
		unset($this->main_class);
		if(isset($this->parent)){
			unset($this->parent);
		}
		return true;
	}
}

class post_parse{
	var $elements = array();
    public $uid=false;
	
	function post_parse($pdata,$uid=false){
        $this->uid = $uid;
		$this->parse($pdata);
		return true;
	}
	
	/*
	 * Recursive function to parse <span class="searchlite">bbcode</span>
	 */
	function parse($post){
		$tags = $this->_tag_array($post);
		$tags = $this->_sort_parent($tags);
		$tags = $this->_process_inner($tags);
		$this->elements = $tags;
	}
	
	private function _process_inner($tags){
		foreach($tags as $t){
			if($t->parent){
				$t->parent->inner[] = $t;
			}
		}
		return $tags;
	}
	
	private function is_text($test){
		if($test === '__'){
			return true;
		}
		return false;
	}
	
	private function _sort_parent($tags){
		$ret = array();
		$parent = 0;//Root elements get a parent of 0
		foreach($tags as $v){
			if($this->is_open($v['tag'])){
                if(!isset($v['attrib'])) $v['attrib'] = '';
				$r = new post_parse_node($v['tag'],$v['attrib'],$parent,$this->uid);
				$r->main_class = &$this;
				if(!$this->is_text($v['tag'])) $parent = $r;
				$ret[] = $r;
			}else{
				$parent = $parent->parent;
			}
		}
		return $ret;
	}
	
	function remove_tag($ref){
		foreach($this->elements as $k=>$e){
			if($e===$ref){
				unset($this->elements[$k]);
			}
		}
	}
	
	function is_open($tag){
		if($tag{0}==='/'||$tag{0}==='\\'){
			return false;
		}
		return true;
	}
	
	private function _tag_array($post){
		$pos = 0;
		$tags = array();
		$open_tag = false;
		$text = '';
		$pr = strlen($post);
		while ( isset($post {$pos})|| $pr>$pos) {
			if($post {$pos}==='['){//open tag
				$open_tag = '';
			}
			if($open_tag===false){
				$text .= $post {$pos};
			}else{//Tag name
				$open_tag .= $post {$pos};
			}
			if($post {$pos}===']'&&strlen($open_tag)){//close
				if(strlen($text)){
					$tags[] = array('tag'=>'__', 'attrib'=>$text);
					$text = '';
				}
				$open_tag = substr($open_tag, 1, strlen($open_tag)-2);
				if(strpos($open_tag,'=')){
					$open_tag = explode('=',$open_tag);
					if($this->uid){
                        $tags[] = array('tag'=>$open_tag[0],'attrib'=>str_replace(':'.$this->uid,'',$open_tag[1]));
                    }else{
                        $tags[] = array('tag'=>$open_tag[0],'attrib'=>$open_tag[1]);
                    }
				}else{
                    if($this->uid){
                        $tags[] = array('tag'=>str_replace(':'.$this->uid,'',$open_tag));
                    }
                    else $tags[] = array('tag'=>$open_tag);
                }
				$open_tag = false;
			}
			$pos ++;
		}
		return $tags;
	}
	
	function clear(){
		foreach($this->elements as $k=>$e){
			if($e instanceof post_parse_node ){
				$e->clear();
				unset($e);
				if($this->elements[$k] instanceof post_parse_node ){
					$this->elements[$k]->clear();
					unset($this->elements[$k]);
				}
			}
		}
		return true;
	}
	
	function find_tag($tag_name){
		$ret = array();
		foreach($this->elements as $tag){
			if($tag->tag === $tag_name){
				$ret[] = $tag;
			}
		}
		return $ret;
	}
	
	function <span class="searchlite">bbcode</span>(){
		$ret = '';
		foreach($this->elements as $tag){
			if($tag->parent===0) $ret .= $tag-><span class="searchlite">bbcode</span>();
		}
		return $ret;
	}
}
 
lmao i sat here looking at this line tihkning wtf lol and then i reailises you must of copied of a php highlighted post lool

$<span class="searchlite">bbcode</span> = '['.$this->tag.($this->attrib?'='.$this->attrib:'').($this->uid?':'.$this->uid:'').']';

should be
$bbcode = '['.$this->tag.($this->attrib?'='.$this->attrib:'').($this->uid?':'.$this->uid:'').']';

lol but yea your code is good but i prefer to keep my code as neat as possible and some rules i follow is trying not to use $array[0] or [1] etc also now using my registry system i can do stuff like

Registry::get('mysql')->query('SELECT * FROM settings')->rows;

the firs section Registry->get('mysql') will retrieve the object out of the registry array then you follow on to access the mysql class and run the query function and then as i use an stdClass i just call for the rows or row cound or just the single row... this is a real times saver :G

but yea good code dood
 
LOL, yeah I copied it from a post I made, this code isnt the neatest. It was my first dabble in making a dom class. Really it is quite an advanced peice of code hence why it makes little sence to most.

Im not really a fan of registry classes, they add quite alot of overhead to page generation. I find its better to just have a few classes that are always defined as the same variable e.g $db, $acl, $user etc.

I think Ill post a download to ddl2 rc1 in this thread for you take a look and give me an honest code review before I release normally if your up for it.
 
Nice OOP both of you, would you do me a favour and do it like
Code:
public function yay()
{
    echo 'yay';
}

instead of

Code:
public function yay(){
echo 'yay';
}

Makes it very much neater, thanks.
 
Nice OOP both of you, would you do me a favour and do it like
Code:
public function yay()
{
    echo 'yay';
}

instead of

Code:
public function yay(){
echo 'yay';
}

Makes it very much neater, thanks.
PHP:
public function yay(){
    echo 'yay';
}

is the proper way ;)
 
All depends on which coding standard you follow, I sort of have my own which is based of the phpbb3 one but faster (No use of "") and I do it the

Code:
function spam($haxors){

way.
 
i prefer to have the first brace after the ) and not on the next line.. just makes thinks easier to read. also i love using tabs to depth my code

PHP:
static function get_downloads(){
         return self::downloads(30);
}

also the point about the registry system is i prefer to use this as i do ot need to create several instances or clones of an object in other classes as you can directly call it and as for speed theres a catching system the performs first before registry is instantiated etc so obv nobody gets there code right and everybody is different but even tho theres obv a few tweaks o can do to my code its probably faster than most other peoples

Peace
 
All depends on which coding standard you follow, I sort of have my own which is based of the phpbb3 one but faster (No use of "") and I do it the

Code:
function spam($haxors){
way.
@Cyber - It's what I would call improper way. Most of the professional scripts, would do it the way I pointed.
@splitice - phpbb3 uses the way I pointed. Also, if you are so concerned about speed you should stop using OOP. The way I pointed, hardly makes any difference.
@litewarez - Amen, different coders have different ways.
 
yea becuase when i open up a code file to fix an error or change summit i like to scroll down my code and be able to read it fast, thus time savin and its just how i feel comfortable, and let me say that EVERY WAY IS CORRECT,
 
lol yea MySqli is more of a wrapper for MySql, and by using the comment functions within my own class i can create my connection between MySql and PHP more website specific,

such as the stdClass i use to return from the class and, not my webiste is built around the base functions mysql_* i just run my own premade functions witch to me thats much easier than using a pre built class thats not specific to my website
 
Status
Not open for further replies.
Back
Top