PDA

View Full Version : آموزش: کلاسهای مفید و کارآمد



sargardoon
جمعه 16 اردیبهشت 1390, 02:12 صبح
سلام دوستان،
تصمیم دارم در این تاپیک کلاسهای که در طول یادگیری PHP یاد گرفتم و استفاده کردم رو بذاریم اینجا شاید به درد دیگران دوستان هم خورد، اگر شما هم کلاسی دارید لطفا اینجا به اشتراک بگذارید.

تبدیل عدد به حرف



class NumbWordter
{
private $discrete=array('0'=>'zero','1'=>'one','2'=>'two','3'=>"three",'4'=>"four",'5'=>"five",'6'=>'six','7'=>'seven',
'8'=>'eight','9'=>'nine','10'=>'ten','11'=>'eleven',"12"=>'twelve','13'=>'thirteen','14'=>'fourteen',
'15'=>'fifteen','16'=>'sixteen','17'=>'seventeen','18'=>'eighteen','19'=>'nineteen','-'=>'minus');

private $ten_digit_prefix=array('2'=>'twenty','3'=>'thirty','4'=>'forty','5'=>'fifty','6'=>'sixty',
'7'=>'seventy','8'=>'eighty','9'=>'ninty');

private $mool_array=array('',"thousand,","million,","billion,","trillion,","quadrillion,","quintillion,","sextillion,",
"septillion,","octillion,","nonillion,","decillion,","unidecillion,","duodecillion,","tredecillion,","quattuordecillion,");

private $sentence; //final sentence
private $error; //error if generated

//methods
private function twodigits($num)
{
//displays from 1 to 99
if($num<20)
return $this->discrete[$num];
else
return $this->ten_digit_prefix[substr($num,0,1)].' '.$this->discrete[substr($num,1,1)];
}

//displays three digit numbers
private function threedigits($num)
{
return $this->discrete[substr($num,0,1)].' hundred and '.$this->twodigits(substr($num,1,2));
}

private function decider($num)
{
if(strlen($num)<=2)
return $this->twodigits($num);
else
return $this->threedigits($num);
}

public function convert($num)
{
//return if more than 48 digits
if(strlen($num)>48)
{
$this->error="Number out of bounds";
return $this->error;
}

//check if first
if(substr($num,0,1)=="-")
{
$this->sentence.='minus ';
$num=substr($num,1,strlen($num)-1);
}

if(strlen($num)<=3)
{
$this->sentence.=$this->decider($num);
}
else
{
$k=strrev($num);
for($i=0;$i<strlen($k);$i=$i+3){$arro[]=strrev(substr($k,$i,3));}
//reverse again
$arro=array_reverse($arro);
//print_r($arro);
$mool=ceil(strlen($num)/3);
if((strlen(num)%3)==0){$mool--;}
$this->sentence.=$this->decider($arro[0]).' '.$this->mool_array[$mool];
$mool--;
//leave the first one and prepare string of others
$arrlen=count($arro);
for($i=1;$i<$arrlen;$i++)
{
$this->sentence.=' '.$this->decider($arro[$i]);
if($mool!=0)
{
$this->sentence=' '.$this->sentence.' '.$this->mool_array[$mool];
}
$mool--;
}
}
return ucfirst(trim($this->sentence));
}
}

روش استفاده


$myConverter = new NumbWordter(); //initialize
$text=$myConverter->convert(123); //pass the number you want to convert
echo $text; //will print the words

sargardoon
جمعه 16 اردیبهشت 1390, 02:21 صبح
insert, select, update Database


<?php
// Using OOP PHP to select, update, and insert data in a mysql database

class database
{
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;

private static $instance;

private $connection;
private $results;
private $numRows;

private function __construct() {}

static function getInstance()
{
if(!self::$instance)
{
self::$instance = new self();
}
return self::$instance;
}


// Create Connection to MySQL
function connect($dbhost, $dbuser, $dbpass, $dbname)
{
$this -> dbhost = $dbhost;
$this -> dbuser = $dbuser;
$this -> dbpass = $dbpass;
$this -> dbname = $dbname;

$this -> connection = mysqli_connect($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
}

// Run Query
public function doQuery ($sql)
{
$this -> results = mysqli_query($this -> connection, $sql);
$this -> numRows = $this -> results -> num_rows;
}

// Load the list of data in database
public function loadObjectList()
{
$obj = 'No Results';
if ($this -> results)
{
$obj = mysqli_fetch_assoc($this -> results);
}

return $obj;
}
}
?>



<?php

class dbtable
{
protected $id = null;
protected $table = null;

function __construct() {}

function bind($data)
{
foreach ($data as $key=>$value)
{
$this->$key = $value;
}
}

function load($id)
{
$this -> id = $id;
$dbo = database::getInstance();
$sql = $this -> buildQuery('load');

$dbo -> doQuery($sql);
$row = $dbo -> loadObjectList();
foreach ($row as $key=>$value)
{
if ($key == "id")
{
continue;
}
$this ->$key = $value;
}
}

function store()
{
$dbo = database::getInstance();
$sql = $this -> buildQuery ('store');

$dbo->doQuery($sql);
}

protected function buildQuery($task)
{
$sql ="";
if ($task == 'store')
{
if($this -> id == '')
{
$keys = '';
$values = '';
$classVars = get_class_vars(get_class($this));

$sql .= "INSERT INTO {$this -> table}";
foreach ($classVars as $key=>$value)
{
if ($key == 'id' || $key == 'table')
{
continue;
}

$keys .= "{$key},";
$values .= "'{$this->$key}',";
}
$sql .= "(".substr($keys, 0, -1).") VALUES(".substr($values, 0, -1).")";
} else {
$classVars = get_class_vars(get_class($this));
$sql .= "Update {$this -> table} SET ";
foreach ($classVars as $key=>$value)
{
if ($key == 'id' || $key == 'table')
{
continue;
}

$sql .= "{$key} = '{$this ->$key}',";
}
$sql = substr($sql, 0, -1)." WHERE id = {$this->id}";
}
} elseif ($task == 'load') {
$sql = "SELECT * FROM {$this->table} WHERE id= '{$this->id}'";
}
return $sql;
}
}

?>




<?php

class user extends dbtable
{
var $fname = null;
var $lname = null;
var $email = null;
var $salt = null;
var $password = null;
var $table = "formregs";
}

?>


سه کد بالا را به هر اسمی که دوست دارید ذخیره کرده و در فایل اصلی include کنید و به روش زیر استفاده کنید.


$dbo = database::getInstance();
$dbo -> connect ('localhost','root','','phptut');
$user = new user();


INSERT data:


$data = array(
"fname" => "xyz",
"lname" => "abc",
"email" => "moham@gmail.com",
"salt" => "3aad88dbb39c5a78e7a66fc09b90dd7d87060c4b",
"password" => "1b514c14862ff0759405c185e9ed07377163532a"
);

$user -> bind($data);
$user -> store();


SELECT Data

$user -> load ('9');
echo "{$user -> fname} {$user -> lname}"; //Display only fname, and lname


UPDATE Data

$user = new user();
$user -> load ('9');
$data = array (
"fname" => "Mohammad Moosa",
"lname" => "Falamarzi Bandari Baloch"
);
$user -> bind($data);
$user -> store();

sargardoon
جمعه 16 اردیبهشت 1390, 02:25 صبح
ساخت فایل Log به صورت متنی


<?php

class Log
{

private $_FileName;
private $_Data;

/**
* @desc Write to a file
* @param str $strFileName Then name of the file
* @param str $strData Data to be append to the file
*/
public function Write($strFileName, $strData)
{
// Set Class Vars
$this -> _FileName = $strFileName;
$this -> _Data = $strData;

// Check Data
$this -> _CheckPermission();
$this -> _CheckData();

$handle = fopen($strFileName, 'a+');
fwrite($handle, $strData."\r");
}

/**
* @desc Read from a file
* @param str $strFileName Then name of the file
* @return str The text file
*/
public function Read($strFileName)
{
$this -> _FileName = $strFileName;

$this -> _CheckExists();

$handle = fopen($strFileName, 'r');
return file_get_contents($strFileName);
}


private function _CheckExists()
{
if (!file_exists($this -> _FileName))
die ('The file does not exists');
}

private function _CheckPermission()
{
if (!is_writable($this -> _FileName))
die ('Change you CHMOD permission to '.$this -> _FileName);
}

private function _CheckData()
{
if (strlen($this -> _Data) < 1)
die ('You must have more than one character to write on the file');
}

}
?>

روش استفاده:

$Log = new Log();
$Log -> Write('test.txt', 'I am from Bolghan');
$strPrint = $Log -> Read('test.txt');
echo str_replace("\r","<br />", $strPrint);

sargardoon
جمعه 16 اردیبهشت 1390, 02:28 صبح
ارزیابی داده های فورم

<?php

class Validation
{
public $errors = array();

public function isValidStr($strVal, $strType, $minChar=2, $maxChar = 1000) {
if(strlen($strVal) < intval($minChar)) {
$this -> setError($strType, ucfirst($strType)." must be at least {$minChar} characters long.");
} elseif (strlen($strVal) > intval($maxChar)) {
$this -> setError($strType, ucfirst($strType)." must be less than {$maxChar} characters long.");
} else {
// validate data entry
$pattern = "#^[\s\x{0621}-\x{063A}\x{0640}-\x{0691}\x{0698}-\x{06D2}\x{06F0}-\x{06F9}\x{0661}-\x{0669}0-9\n\r\\'\-\_\.\:\,0-9a-zA-Z]+$#u";
if (!preg_match($pattern, $strVal)) {
$this -> setError($strType, ucfirst($strType)." must be from letters, dashes, spaces and must not start with dash");
}
}
}

public function isValidEmail($emailVal) {
if(strlen($strVal) < 0 ) {
$this -> setError('email', 'E-mail Address cannot be blank');
} else {
// validate data entry
$pattern = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";
if (!preg_match($pattern, $emailVal)) {
$this -> setError('email', 'Please enter valid E-mail Address');
}
}
}


public function isValidURL($urlVal) {
if(!empty($urlVal)) {
$pattern = "#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i";
if (!preg_match($pattern, $urlVal)) {
$this -> setError('url', 'Please enter valid URL Address with http://');
}
}
}


public function setError($key, $value) {
$this -> errors[$key] = $value;
}

public function getError($key) {
if ($this -> errors[$key]) {
return $this -> errors[$key];
} else {
return false;
}
}


public function errCount() {
return (count($this -> errors) > 0) ? count($this -> errors) : false;
}
}

?>

روش استفاده

<?php

if (isset($_POST['submit'])) {
require_once "validation.class.php";

$name = trim($_POST['name']);
$email = trim($_POST['email']);
$website = trim($_POST['website']);

$validate = new Validation();
$validate -> isValidStr($name, 'name', 2, 32);
$validate -> isValidEmail($email);
$validate -> isValidURL($website);

if (!$validate -> errCount()) {
echo '<h3>You have Successfully Registered</h3>';
echo "Name: {$name} | Email: {$email} | Website: {$website}";
} else {
$errCount = $validate -> errCount();
$errCount = 'There were '.$errCount.' errors, Please fill the required fields';
$errName = $validate -> getError('name');
$errEmail = $validate -> getError('email');
$errURL = $validate -> getError('url');
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Class :: Validation Form</title>
</head>
<body>
<form action="" method="post">
<?php echo '<h4>'.$errCount.'</h4>'; ?>
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>Name:</td>
<td>
<input type="text" name="name" value="<?php echo htmlentities($name); ?>" /><br />
<?php echo $errName; ?>
</td>
</tr>
<tr>
<td>email:</td>
<td>
<input type="text" name="email" value="<?php echo htmlentities($email); ?>" /><br />
<?php echo $errEmail; ?>
</td>
</tr>
<tr>
<td>website:</td>
<td>
<input type="text" name="website" value="<?php echo htmlentities($website); ?>" /><br />
<?php echo $errURL; ?>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value=" Register " /></td>
</tr>
</table>
</form>
</body>
</html>

sargardoon
جمعه 16 اردیبهشت 1390, 02:29 صبح
برای امروز اینها را داشته باشید تا سرفرصت چندتای دیگری هم بذارم، از اینکه کدها طولانیه معذرت میخوام، امیدوارم که به درد دوستان بخوره، لطفا از پست های بی ربط خوداری کنید.