آموزش برنامه نویسی Oop

hidensoft

Member
Strategy Pattern یا input Validator

بی شک یکی از مشکلات برنامه نویسان Valid کردن اطلاعات ورودی هست . معمولا هم ما با استفاده از IF ... ELSE کار خودمونو راه می ندازیم. اما بهتره از Strategy Pattern استفاده بشه . بی شک به شما خیلی بیشتر کمک می کنه . برنامه هم خانایی بیشتری پیدا می کنه .
بهتره بریم سر اصل مطلب .

validator.php

PHP:
<?php
/**
 *  کلاس اصلی
 */
class Validator {
    /**
    * Private
    * $errorMsg نگهداری خطا ها در صورت وجود
    */
    var $errorMsg;

    //! A constructor.
    /**
    * ساخت یک شی validator جدید
    */
    function Validator () {
        $this->errorMsg=array();
        $this->validate();
    }

    /**
    * @return void
    */
    function validate() {
       
    }

    /**
    * اضافه کردن خطا به آرایه
    * @return void
    */
    function setError ($msg) {
        $this->errorMsg[]=$msg;
    }

    /**
    * بازگشت درست و غلط 
    * @return boolean
    */
    function isValid () {
        if ( isset ($this->errorMsg) ) {
            return false;
        } else {
            return true;
        }
    }

    /**
    *  بدست آوردن خطا ها
    * @return string
    */
    function getError () {
        return array_pop($this->errorMsg);
    }
}

/**
 *valid کردن username
 */
class ValidateUser extends Validator {
    /**
    * $user متغیر مورد نیاز
    */
    var $user;

    /**
    * اخت یک شی validatoruser جدید
    * @param $user the string to validate
    */
    function ValidateUser ($user) {
        $this->user=$user;
        Validator::Validator();
    }

    /**
    * Validates کردن username
    * @return void
    */
    function validate() {
        if (!preg_match('/^[a-zA-Z0-9_]+$/',$this->user )) {
            $this->setError('Username contains invalid characters');
        }
        if (strlen($this->user) < 6 ) {
            $this->setError('Username is too short');
        }
        if (strlen($this->user) > 20 ) {
            $this->setError('Username is too long');
        }
    }
}

/**
 *  Validate کردن  password
 */
class ValidatePassword extends Validator {
    /**
    * $pass متغیر مورد نیاز
    */
    var $pass;
    /**
    * $conf متغیر تکرار کلمه عبور
    */
    var $conf;

    /**
    * ساخت ValidatePassword شی جدید
    * @param $pass the string to validate
    * @param $conf to compare with $pass for confirmation
    */
    function ValidatePassword ($pass,$conf) {
        $this->pass=$pass;
        $this->conf=$conf;
        Validator::Validator();
    }

    /**
    * Validates کردن  password
    * @return void
    */
    function validate() {
        if ($this->pass!=$this->conf) {
            $this->setError('Passwords do not match');
        }
        if (!preg_match('/^[a-zA-Z0-9_]+$/',$this->pass )) {
            $this->setError('Password contains invalid characters');
        }
        if (strlen($this->pass) < 6 ) {
            $this->setError('Password is too short');
        }
        if (strlen($this->pass) > 20 ) {
            $this->setError('Password is too long');
        }
    }
}

/**
 *  Validates کردن email address
 */
class ValidateEmail extends Validator {
    /**
    * $email متغیر مورد نیاز
    */
    var $email;

    /**
    * جدید ValidateEmail ساخت شی
    * @param $email the string to validate
    */
    function ValidateEmail ($email){
        $this->email=$email;
        Validator::Validator();
    }

    /**
    * Validates کردن email address
    * @return void
    */
    function validate() {
        $pattern=
    "/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/";
        if(!preg_match($pattern,$this->email)){
            $this->setError('Invalid email address');
        }
        if (strlen($this->email)>100){
            $this->setError('Address is too long');
        }
    }
}
?>

index.php

PHP:
<?php
if ( $_POST['register'] ) {
    require_once('lib/Validator.php');

    $v['u']=new ValidateUser($_POST['user']);
    $v['p']=new ValidatePassword($_POST['pass'],$_POST['conf']);
    $v['e']=new ValidateEmail($_POST['email']);

    foreach($v as $validator) {
        if (!$validator->isValid()) {
            while ($error=$validator->getError()) {
                $errorMsg.="<li>".$error."</li>\n";
            }
        }
    }
    if (isset($errorMsg)) {
        print ("<p>There were errors:<ul>\n".$errorMsg."</ul>");
    } else {
        print ('<h2>Form Valid!</h2>');
    }
} else {
?>
<h2>Create New Account</h2>
<form action="<?php echo ($_SERVER['PHP_SELF']); ?>" method="post">
<p>Username: <input type="text" name="user"></p>
<p>Password: <input type="password" name="pass"></p>
<p>Confirm: <input type="password" name="conf"></p>
<p>Email: <input type="text" name="email"></p>
<p><input type="submit" name="register" value=" Register "></p>
</form>
<?php
}
?>

فکر نمی کنم نیاز به توضیح خاصی باشه .
موفق باشید.
 

پیوست ها

  • Strategy Pattern Sample.zip
    1.6 کیلوبایت · بازدیدها: 41
آخرین ویرایش:

hidensoft

Member
سلام
امید وارم که آموزش های قبلی به شما کمک کرده باشه که در برنامه نویسی PHP پیشرفت داشته باشید .
امروز می خوام براتون یک کلاس رو بگذارم . این کلاس به شما کمک می کنه خیلی راحت اواع کوئری رو انجام بدید و خیالتون راحت باشه که هیچ وقت SQL Injection نمی تونه به برنامه شما نفوذ کنه .
PHP:
<?php

class mysql {

    // Database server information
    var $host;                 // (string)  Host server of database
    var $user;                 // (string)  User
    var $password;             // (string)  Password
    var $db_name;              // (string)  Database that will be selected
    var $port;                 // (int)     Server port
    var $connection = false;   // (link identifier)   MySQL connection link identifier
    var $result;               // (link identifier)   MySQL result link identifier
    
    // Class operation setup
    
    
    // 0 LOG_NONE
    // 1 ECHO
    // 2 HIDDEN ECHO
    // 3 LOG FILE
    var $debuglv  = 2 ;
    var $error_level  = 0 ;
    var $error_desc   = "No errors" ;
    var $logfile      = "datalog" ;
    var $filehdl      = 0 ;
    var $messsages    = array() ;  
      
    var $affected_rows = 0 ;    
    var $num_rows      = 0 ;    
    var $recordcount   = 0 ;    
    var $lastid        = 0 ;
    var $sqlString;
    
    var $query_no     = 0 ;    



    function mysql($host = "", $user = "", $password = "", $db_name = "", $port = "")
    {
        $this->host     = ( !empty( $host ) )      ?  (string)$host      :  "localhost";
        $this->user     = ( !empty( $user ) )      ?  (string)$user      :  "root";
        $this->password = ( !empty( $password ) )  ?  (string)$password  :  "";
        $this->db_name  = ( !empty( $db_name ) )   ?  (string)$db_name   :  "";
        $this->port     = ( !empty( $port ) )      ?  (int)$port         :  3306;
    }




    function connect($is_persistent = false)
    {                
        $this->logfile_init() ;

        if (!$is_persistent) {
            $this->connection = @mysql_connect($this->host.':'.$this->port, $this->user, $this->password);
        } else {
            $this->connection = @mysql_pconnect($this->host.':'.$this->port, $this->user, $this->password);
        }
        $this->error_report() ;
        
        if (!$this->connection) {
          // Conection failed
          $this->add_debug_message ( date("d/m/Y - H:i:s") . " - ERROR " . $this->error_level . ": " . $this->error_desc . "\r\n" ) ;          
          $this->release_db() ;
        } else { $this->select_db(); }        
    }

    function  select_db($db_name=false){
         if ($db_name !== false) $this->db_name=$db_name;
        
      // Select a database...
      if (@mysql_select_db($this->db_name,$this->connection)) {
        // Selecting Database OK
        $this->add_debug_message ( date("d/m/Y - H:i:s") . " - OPERATION O.K.: Connected to database " . $this->db_name .  "\r\n" );
      } else {
        // Failed to select the database... abort connection process
        $this->error_report() ;
        $this->add_debug_message ( date("d/m/Y - H:i:s") . " - ERROR " . $this->error_level . ": " . $this->error_desc . "\r\n" ) ;
        $this->release_db() ;
        }                
    }
    
  // Releasing database connection
  function release_db()
    {
    // Checking if a conection is open?
    if ($this->connection) {
      // Trying to close the connection ...
      if (mysql_close($this->connection)) {
        $this->add_debug_message ( date("d/m/Y - H:i:s") . " - OPERATION O.K.: Database " . $this->db_name . " released" . "\r\n" );
      } else {
        // Failed to liberate the database...
        $this->error_report() ;
        $this->add_debug_message ( date("d/m/Y - H:i:s") . " - ERROR " . $this->error_level . ": " . $this->error_desc . "\r\n" );
        }
    } else {
      // No database open
      $this->add_debug_message ( date("d/m/Y - H:i:s") . " - OPERATION CANCELLED: No database open" . "\r\n" );
      }
    // LOG the operation and close logging operations
    $this->debug() ;
    $this->logfile_close() ;
    }
    

  // Error reporting auxiliary method
  function error_report()
    {
    $this->error_level = mysql_errno() ;
    $this->error_desc = mysql_error() ;
    }

  // Log operations initialization
  function logfile_init()
    {      
    if ($this->debuglv==3) {
         $this->add_debug_message ( date("d/m/Y - H:i:s") . " ===== SESSION STARTED BY " . $GLOBALS["PHP_SELF"] . " =====" .  "\r\n" );
         $this->logfile = $this->logfile . "-" . date("m") . "-" . date("Y") ;
         $this->filehdl = fopen($this->logfile,'a') ;
         if (!$this->filehdl) {
                echo "<!-- UNABLE TO OPEN SPECIFIED LOG FILE " . $this->logfile . " -->" ;
                $this->debuglv-- ;
                $this->logfile_init() ;
                }
              break ;
      }
    $this->debug() ;
    }
    
  // Closing log operations
  function logfile_close()
    {
    if ($this->filehdl) {
      // If we opened a file to log operations need to close it
      fclose($this->filehdl) ;
      }
    }

  function add_debug_message($message)
    {
        $this->messsages[]=$message;
    }

  // Debugging operations
  function debug()
    {
    switch ($this->debuglv) {
      case 0: // NO LOG OPERATIONS
              break ;
      case 1: // SCREEN OUTPUT
              foreach ($this->messsages as $m) {
                echo '<BR>DEBUG: ' . $m . '<BR>' ;
              }  
              break ;
      case 2: // SILENT OUTPUT (<!-- -->)
              foreach ($this->messsages as $m) {
                echo "\n<!-- DEBUG: " . $m . "-->\n" ;
              }  
              break ;
      case 3: // FILE OUTPUT
              foreach ($this->messsages as $m) {
                fwrite($this->filehdl,$this->msg) ;
              }  
              break ;
      }
    }    


  // Destructor
    function destroy()
      {
        $this->release_db() ;
      }
    
      
    // performes an sqlQuery
    function query($sqlString)
      {
          $this->sqlString=$sqlString;
          $this->query_no++;  
          
        if ($this->connection !== false) {
          $this->result = mysql_query($sqlString,$this->connection) ;    
          $this->error_report() ;
          // Affectected rows...
          if ($this->result) {
            // Execution was o.k.          
            $this->affected_rows = mysql_affected_rows( $this->connection );
            if (is_resource($this->result)) {
                $this->num_rows = mysql_num_rows( $this->result );
            } else $this->num_rows = 0;
            $this->lastid = mysql_insert_id( $this->connection );
            $this->add_debug_message( date("d/m/Y - H:i:s") . " - OPERATION O.K.: Executed [" . $this->sqlString ."] [affected " . $this->affected_rows . " rows] [rows in result " . $this->num_rows . " ]" . "\r\n" );
            return true;
          } else {
            // Execution Failed
            $this->affected_rows = 0 ;      
            $this->num_rows = 0 ;      
            $this->add_debug_message( date("d/m/Y - H:i:s") . " - OPERATION FAILED: Executed [" . $this->sqlString . "] got " . $this->error_level . " " . $this->error_desc . "\r\n" );
            return false;
            }
        } else {
          // No database ready to query
          $this->affected_rows = 0 ;
          $this->num_rows = 0 ;
          $this->add_debug_message( date("d/m/Y - H:i:s") . " - OPERATION FAILED: No database open OR no SQL command provided" . "\r\n"  );
          return false;
          }          
      }
      
    function fetch_assoc( $result = false )
       {
            if ( $result === false ) $result = $this->result;
        return mysql_fetch_assoc( $result  );
       }
    
    function clean_data($data)
      {
      return mysql_real_escape_string($data,$this->connection);    
      }

    function fetch_data_array ()
       {
        $data=array();
        while( $row = $this->fetch_assoc() )
            { $data[]=$row; }
        return $data;    
       }

    // grabs a list of rows from a tabel ... returnes an array of data  
    function list_table( $table_name, $where = false, $parameters = array () )
       {
        $range       = ( isset($parameters['range'])       && !empty($parameters['range']) )       ? $parameters['range']       : " * " ;
        $sortColumn  = ( isset($parameters['sortColumn'])  && !empty($parameters['sortColumn']) )  ? $parameters['sortColumn']  : false ;
        $sortType    = ( isset($parameters['sortType'])    && !empty($parameters['sortType']) )    ? $parameters['sortType']    : "ASC" ;
        $limitOffset = ( isset($parameters['limitOffset']) && !empty($parameters['limitOffset']) ) ? $parameters['limitOffset'] : false ;
        $rowCount    = ( isset($parameters['rowCount'])    && !empty($parameters['rowCount']) )    ? $parameters['rowCount']    : false ;
        
        $queryString= "SELECT $range FROM $table_name ";
        if ( $where !== false ) $queryString .= " WHERE ".$where;
        if ( $sortColumn !== false ) $queryString .= " ORDER BY `$sortColumn` $sortType ";        
        if ( $rowCount !== false ) {
            $queryString .= " LIMIT ";
            if ( $limitOffset !== false ) $queryString .= " $limitOffset, ";
            $queryString .= " $rowCount ";
        }
        
        $this->query($queryString);
        if( $this->num_rows < 1 ) { return false; }
        else { return $this->fetch_data_array(); }
      }

    // fetch a row from a table
    function fetch_row( $table_name, $where = false , $parameters = array () )
      {
      $range       = ( isset($parameters['range'])       && !empty($parameters['range']) )       ? $parameters['range']       : " * " ;
      $range       = ( isset($parameters['range'])       && !empty($parameters['range']) )       ? $parameters['range']       : " * " ;
                  
        $queryString= "SELECT $range FROM $table_name ";
        if ( $where != false ) $queryString .= " WHERE $where LIMIT 1";

      $this->query($queryString);    

      if( $this->num_rows < 1 ) { return false; }
      else { return $this->fetch_assoc(); }              
        }

    function count_records( $table_name, $where =false , $parameters = array() )
        {                        
        $queryString= "SELECT COUNT(*) as rNumber FROM $table_name ";
        if ( $where != false ) $queryString .= " WHERE $where ";
      if ($this->query($queryString) == true ){
          $row=$this->fetch_assoc();
          return $row["rNumber"];
      } else return false;      
        }
        
    function increment_field( $table_name, $field, $where, $parameters = array() )
      {
        $queryString= "UPDATE $table_name SET `$field`=`$field`+1  WHERE $where ";
      $this->query($queryString);               
      }

    function record_update( $table_name, $data, $where, $parameters = array() )
      {
      $queryString="UPDATE ".$table_name." SET ";
      $fields=array();
        
      foreach ($data as $key=>$value)    {
          $fields[] = " `$key`='".$this->clean_data( $value )."' ";
      }
      $queryString .= implode(',',$fields)." WHERE ".$where;        
        
      return $this->query($queryString);               
      }

    function record_insert( $table_name, $data, $parameters = array() )
      {
      $queryString="INSERT INTO ".$table_name." (";  
      $columns=array();        
      $values=array();
      
      foreach ($data as $key=>$value)
          {
              $columns []= '`'.$key.'`';
              $values  []= "'".$this->clean_data( $value )."'";
        }      
          
      $queryString .= implode(',',$columns) .") VALUES (". implode(',',$values) .") ";          
      
      return $this->query($queryString);                     
      }
 
    function record_delete( $table_name, $where, $parameters = array() )
      {
      $queryString = "DELETE FROM ". $table_name ." WHERE ". $where;
      $this->query($queryString);                               
      }      

    function table_info($table_name)
      {
       $this->query(" SELECT * FROM $table_name LIMIT 1");                               
       $fields = mysql_num_fields($this->result);
    
       for ($i=0; $i <= $fields; $i++) {
         $fields[$i]['type'] = mysql_field_type($result, $i);
         $fields[$i]['name'] = mysql_field_name($result, $i);
         $fields[$i]['len']  = mysql_field_len($result, $i);
       }
    
    return $fields;
    }

   function table_max_value( $table, $field)
     {
     $this->query(" SELECT max($field) as max_value FROM $table ");
     $data=$this->fetch_assoc();

     return $data["max_value"];
     }
    
}
?>
این هم نمونه استفاده از این کلاس

PHP:
 <?php

// conection
$mysql= new mysql('localhost' , 'userSQL', 'passwSQL', 'Selected_DB' );
$mysql->connect();

// fetch row
$row=$mysql->fetch_row( 'TableName', " id='12' ");

// fetch array of rows
$rows=$mysql->list_table( 'TableName', " column='3' ", array ('range' => 'id,name') );  

// fetch rows from multiple tables
$rows=$mysql->list_table( ' TableName1 t1,TableName1 t2 ', " t1.column1=t2.column2 ", array ('range' => ' t1.column1_1, t2.column1_2 ') );  


// fetch whole table
$tableList=$mysql->list_table( 'TableName', false ,  );


// fetch a part of a table - pagination example  
$parameters['limitOffset']=10; # Offet Start  
$parameters['rowCount']=10; # No of rows returned
$where=" columnName='3' ";
$tableList=$mysql->list_table( 'TableName', where , $parameters );

$data=array('columnName1' => 'value1',
            'columnName2' => 'value2',
            'columnName3' => 'value3',        
            );        
// insert data ... it returns true or false
$insertAtempt=$mysql->record_insert('TableName',$data);

// update data
$updateAtempt=$mysql->record_update('TableName',$data," id='3' ");  

    
?>
این یه آموزش نبود اما شما با استفاده از این کلاس هم کارتون راحت تر میشه هم با نگاه کردن به کدش می تونید چیزای جدیدی یاد بگیرید.

موفق و پیروز باشید
 

Allahparast

Member
ممنونم هیدن جان خسته هم نباشید اگه میشه یه بار دیگه این اسمارتی و مفاهمش رو به صورت کامل توضیح بده
من دیدم دو سه نفر از تابع str_replace & sub_str و غیره این اسمارتی رو به ده خط تبدیل می کنند ممنون خواهش کمکم کنید چون احتیاج دارم راستی بگین چطور توش کوئری رو سلکت کنم :)
 

hidensoft

Member
آموزش Smarty رو سیاوش به عهده گرفته . اگه سوالی دارید از ایشون سوال بفرمایید .
 

zoghal

Active Member
سلام دوستان .
امروز نوبت ساختن یک mvc سادست.
در ابتدا این تمام کد هارو می نویسم . شما سوال حاتون رو بپرسید . من و دیگر دوستان هر زمان که بتونیم جواب می دیم.

Index.php
PHP:
<?php
require_once('lib/dataaccess.php');
require_once('lib/productmodel.php');
require_once('lib/productview.php');
require_once('lib/productcontroller.php');

$dao=& new dataaccess ('localhost','user','pass','dbname');
$productmodel=& new productmodel($dao);
$productcontroller=& new productcontroller($productmodel,$_get);
echo $productcontroller->display();
?>

lib/productview.php
PHP:
<?php
/**
 *  binds product data to html rendering
 */
class productview {
    /**
    * private
    * $model an instance of the productmodel class
    */
    var $model;

    /**
    * private
    * $output rendered html is stored here for display
    */
    var $output;

    //! A constructor.
    /**
    * constucts a new productview object
    * @param $model an instance of the productmodel class
    */
    function productview (&$model) {
        $this->model=& $model;
    }

    //! A manipulator
    /**
    * builds the top of an html page
    * @return void
    */
    function header () {
        $this->output=
		<<<eod
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title> our products </title>
<style>
body { font-size: 13.75px; font-family: Verdana }
td { font-size: 13.75px; font-family: Verdana }
.title { font-size: 15.75px; font-weight: Bold; font-family: Verdana }
.heading {
    font-size: 13.75px; font-weight: Bold;
    font-family: Verdana; background-color: #f7f8f9 }
.nav { background-color: #f7f8f9 }
</style>
</head>
<body>
<div align="center" class="title">our products</div>
eod;
        $this->output.="\n<div align=\"right\"><a href=\"".
            $_server['php_self']."\">start over</a></div>\n";

    }

    //! A manipulator
    /**
    * builds the bottom of an html page
    * @return void
    */
    function footer () {
        $this->output.="</body>\n</html>";
    }

    //! A manipulator
    /**
    * displays a single product
    * @return void
    */
    function productitem($id=1) {
        $this->model->listproduct($id);
        while ( $product=$this->model->getproduct() ) {
            $this->output.="<p><b>name</b>:".$product['productname']."</p>".
                "<p><b>price</b>:".$product['unitprice']."</p>".
                "<p><b># in stock</b>:".$product['unitsinstock']."</p>";
            if ( $this->$product['discontinued']==1 ) {
                $this->output.="<p>this product has been discontinued.</p>";
            }
        }
    }

    //! A manipulator
    /**
    * builds a product table
    * @return void
    */
    function producttable($rownum=1) {
        $rowsperpage='20';
        $this->model->listproducts($rownum,$rowsperpage);
        $this->output.="<table width=\"600\" align=\"center\">\n<tr>\n".
                "<td class=\"heading\">name</td>\n".
                "<td class=\"heading\">price</td>\n</tr>\n";
        while ( $product=$this->model->getproduct() ) {
            $this->output.="<tr>\n<td><a href=\"".$_server['php_self'].
                "?view=product&id=".$product['productid']."\">".
                $product['productname']."</a></td>".
                "<td>".$product['unitprice']."</td>\n</tr>\n";
        }
        $this->output.="<tr class=\"nav\">\n";
        if ( $rownum!=0 && $rownum > $rowsperpage ) {
            $this->output.="<td><a href=\"".$_server['php_self'].
                "?view=table&rownum=".($rownum-$rowsperpage).
                "\"><< prev</a></td>";
        } else {
            $this->output.="<td>&nbsp;</td>";            
        }
        if ( $product['productid'] < ($rownum + $rowsperpage) ) {
            $this->output.="<td><a href=\"".$_server['php_self'].
                "?view=table&rownum=".($rownum+$rowsperpage).
                "\">next >></a></td>";
        } else {
            $this->output.="<td>&nbsp;</td>\n";            
        }
        $this->output.="</tr>\n</table>\n";
    }

    //! An accessor
    /**
    * returns the rendered html
    * @return string
    */
    function display () {
        return $this->output;
    }
}
?>

lib/productcontroller.php
PHP:
<?php
/**
 *  controls the application
 */
class productcontroller extends productview {

    //! A constructor.
    /**
    * constucts a new productcontroller object
    * @param $model an instance of the productmodel class
    * @param $getvars the incoming http get method variables
    */
    function productcontroller (&$model,$getvars=null) {
        productview::productview($model);
        $this->header();
        switch ( $getvars['view'] ) {
            case "product":
                $this->productitem($getvars['id']);
                break;
            default:
                If ( empty ($getvars['rownum']) ) {
                    $this->producttable();
                } else {
                    $this->producttable($getvars['rownum']);
                }
                break;
        }
        $this->footer();
    }
}
?>

lib/productmodel.php
PHP:
<?php
/**
 *  fetches "products" from the database
 */
class productmodel {
    /**
    * private
    * $dao an instance of the dataaccess class
    */
    var $dao;

    //! A constructor.
    /**
    * constucts a new productmodel object
    * @param $dbobject an instance of the dataaccess class
    */
    function productmodel (&$dao) {
        $this->dao=& $dao;
    }

    //! A manipulator
    /**
    * tells the $dboject to store this query as a resource
    * @param $start the row to start from
    * @param $rows the number of rows to fetch
    * @return void
    */
    function listproducts($start=1,$rows=50) {
        $this->dao->fetch("select * from products limit ".$start.", ".$rows);
    }

    //! A manipulator
    /**
    * tells the $dboject to store this query as a resource
    * @param $id a primary key for a row
    * @return void
    */
    function listproduct($id) {
        $this->dao->fetch("select * from products where productid='".$id."'");
    }

    //! A manipulator
    /**
    * fetches a product as an associative array from the $dbobject
    * @return mixed
    */
    function getproduct() {
        if ( $product=$this->dao->getrow() )
            return $product;
        else
            return false;
    }
}
?>

dataaccess.php
PHP:
<?php
/**
 *  a simple class for querying mysql
 */
class dataaccess {
    /**
    * private
    * $db stores a database resource
    */
    var $db;
    /**
    * private
    * $query stores a query resource
    */
    var $query; // query resource

    //! A constructor.
    /**
    * constucts a new dataaccess object
    * @param $host string hostname for dbserver
    * @param $user string dbserver user
    * @param $pass string dbserver user password
    * @param $db string database name
    */
    function dataaccess ($host,$user,$pass,$db) {
        $this->db=mysql_pconnect($host,$user,$pass);
        mysql_select_db($db,$this->db);
    }

    //! An accessor
    /**
    * fetches a query resources and stores it in a local member
    * @param $sql string the database query to run
    * @return void
    */
    function fetch($sql) {
        $this->query=mysql_unbuffered_query($sql,$this->db); // perform query here
    }

    //! An accessor
    /**
    * returns an associative array of a query row
    * @return mixed
    */
    function getrow () {
        if ( $row=mysql_fetch_array($this->query,mysql_assoc) )
            return $row;
        else
            return false;
    }
}
?>
محمد جان کاش یک توضیحی در مورد نحوه کارش میدادی
 
از بررسی ایجادی که برای کلاس های SQL نوشته بودی خوشم اومد ... جالب بود ...

ولی به نظرم یه اشکالی داره اینه که بدجوری با array مچه ... آرایه ها وظیفشون به نظر من نگهداری اطلاعات به صورت چند بخشی به مدتهای زیاد نیست، چون میزان پروسس PHP هرچقدرم که بالا باشه به سرور هم بستگی داره ...

در هر صورت نحوه جالبی برای پردازش اطلاعات واسه دیتابیس بود ...

موفق باشید/.
 

Y.P.Y

Well-Known Member
پیشنهاد می کنم وقتی که آموزشی رو شروع می کنید(مخصوصاً مقدماتی)، از همونجا استاندارد ها ور هم در کنارش قرار بدید.
 

ali0480

Member
من تصمیم گرفتم زبان pHp رو یاد بگیرم لطفا اگه براتون مقدور هستش یه منبع آموزشی به من معرفی کنید ؟
لطف کنید PDF باشه
ممنون
 

hidensoft

Member
پیشنهاد می کنم وقتی که آموزشی رو شروع می کنید(مخصوصاً مقدماتی)، از همونجا استاندارد ها ور هم در کنارش قرار بدید.
من هم همین کارو کردم !
من تصمیم گرفتم زبان php رو یاد بگیرم لطفا اگه براتون مقدور هستش یه منبع آموزشی به من معرفی کنید ؟
لطف کنید pdf باشه
ممنون
اینجا تاپیک آموزش برنامه نویسی oop با php هست ، جستجو کنید حتما مورد های بهتری رو پیدا می کنید.
 

Y.P.Y

Well-Known Member
پیشنهاد می کنم وقتی که آموزشی رو شروع می کنید(مخصوصاً مقدماتی)، از همونجا استاندارد ها ور هم در کنارش قرار بدید.
من هم همین کارو کردم!
مثلاً:
[LTR]
final class Myclass
{
final public function print_my_name()
{
echo($this->myname);
}

final private function set_my_name($name)
{
$this->myname= $name;
}
};
[/LTR]
 

yakoza

Well-Known Member
بنا به سوال يكي از كاربرا تو اين قسمت مي خوام درباره چند تا از Magic Methods هاي php صحبت كنم

در مورد تابع clone


PHP:
class CopyMe {}
$first = new CopyMe();
$second = $first;
تو php4 وقتي اين كد رو اجرا ميكردي $first و $second دو تا شي مجزا بودن ولي تو php5 با اجراي اين كد $first به $second رفرنس ميده يعني چي ؟ يعني اينكه هر تغييري تو $first بيوفته تو $second هم اعمال ميشه

حالا يه وقت هست ما مي خواييم تابع رو كپي كنيم و رفرنس نديم تو اين جا مياييم از clone استفاده ميكنيم

يه مثال ميزنم بهتر جا بيوفته
PHP:
<?php
class copyme
{
	public $name="naser";

}

$first=new copyme();
echo $first->name."<br>";
$second=$first;
$second->name="ahmad";
echo $first->name."<br>";
echo $second->name;
?>
خروجي كد بالا چيه

کد:
naser
ahmad
ahmad

حالا به مثال زير توجه كن
PHP:
<?php
class copyme
{
	public $name="naser";

}

$first=new copyme();
echo $first->name."<br>";
$second=clone $first;
$second->name="ahmad";
echo $first->name."<br>";
echo $second->name;
?>

به خروجيش توجه كن ببين چه فرقي با قبلي كرد

کد:
naser
naser
ahmad

حالا يه موقع هست كه شما مي خوايي از كپي شدن يه تابع جلوگيري كني

PHP:
<?php
class copyme
{
	public $name="naser";
	
	public function __clone()
	{
		die("can't copy this object");
	}
}

$first=new copyme();
echo $first->name."<br>";
$second=clone $first;
$second->name="ahmad";
echo $first->name."<br>";
echo $second->name;
?>

خروجيش هم ميشه
کد:
naser
can't copy this object
 

X7337X

Member
خیلی خوب توضیح دادی

میشه در مورد get & set هم به همین صورت توضیح بدی؟
 

yakoza

Well-Known Member
خوب حالا نوبت متدهاي __set و __get رسيد

با استفاده از متدهاي بالا ميشه به اعضاي كلاس دسترسي داشت و اونها رو خوند و تغيير داد حتي اگر اون عضو كلاس به صورت private تعريف شده باشه كه در حالت عادي نميشه يه همچين كاري كرد و به عضو private يه كلاس خارج از اون كلاس دسترسي پيدا كرد

PHP:
<?php
class test
{
	private $data=array("name"=>"Naser","age"=>20);
	
	public function __set($name,$value)
	{
		$this->data[$name]=$value;
	}
	
	public function __get($name)
	{
		if(array_key_exists($name,$this->data))
		{
			return $this->data[$name];
		}
		return FALSE;
	}
}

$test=new test();
echo "my name is ".$test->name." and i'm ".$test->age;
$test->lastname="kholghi";
echo "and my last name is ".$test->lastname;
 
?>

كه خروجيش به ترتيب زيره
کد:
my name is Naser and i'm 20and my last name is kholghi

البته كاربردهاي ديگه اي هم داره كه من فقط به يكيش اشاره كردم كه اصل مطلب جا بيوفته

ارادتمند شما
ناصر
 

hidensoft

Member
با Propel یک قدم به OOP نزدیک شوید


سلام دوستان.
چند روزی در خدمت شما هستم ، امید وارم که تو این مدت بتونم باز هم به برنامه نویس های ایرانی کمک کنم.

Propel یک Object Relational Mapping یا همون ORM هست.
حتما پیش خودتون می گید که چه فایده ای داره که من از Propel استفاده کنم. باید بگم شما با استفاده از Propel که یک فریم ورک بسیارکار آمد برای برقراری ارتباط با دیتابیس هست تمام پایگاه داده خودتون رو بصورت کلاس در میارید و از همه مهم تر شما می تونید به پایگاه های داده MySQL, MS SQL Server, PostgreSQL, SQLite, Oracle وصل بشید.

شما در Propel دیگه نیازی ندارید که برای ساخت database به phpmyadmin یا هر ابزار دیگه ای وصل بشید.
اطلاعات دیتا بیس بصورت کد XML ذخیره می شن و پروپل خودش دیتابیس رو می سازه
برای مثال
HTML:
<database name="bookstore" defaultIdMethod="native">
  <table name="book">
    <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true"/>
    <column name="title" type="varchar" size="255" required="true" />
  </table>
  <table name="author">
    <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true"/>
    <column name="first_name" type="varchar" size="128" required="true"/>
    <column name="last_name" type="varchar" size="128" required="true"/>
  </table>
</database>

سپس کافیه تا دستور زیر رو در command prompt اجرا کنید

کد:
> propel-gen /path/to/bookstore

حالا دیتابیس ساخته شده و پروپل از هر تیبل یک شی می سازه به عنوان مثال برای جدول book دو فایل ایجاد می کنه :
کد:
bookstore/Book.php
bookstore/BookPeer.php
فایل اول کلاس book هست که به BookPeer ارجاء داده شده . BookPeer تمام کلاسی هست که پروپل می سازه و Book برای این ایجاد می شه که شما اگر نیازی داشتید که فانکشنی اضافه کنید اینجا اضافه کنید.

حالا نوبت به این می رسه که دستورات Create, Retrieve, Update, Delete رو اجرا کنیم

جدول author رو در نظر بگیرید. برای Create کافیه که
PHP:
$author = new Author();
$author->setFirstName("Jack");
$author->setLastName("London");
$author->save();
دقیقا این کد در پشت پرده اجرا می شه
کد:
INSERT INTO author (first_name, last_name) VALUES ('Jack', 'London');

دیدید که به چه راحتی می تونید اطلاعات رو اضافه کنید . اگر دقت کرده باشید برای اینکه مقداریبه فیلدی بدید کافیه
کد:
$TableName->setFieldName("value")
در نهایت هم دستور
کد:
$TableName->save()
اطلاعات جدول رو ذخیره می کنه .

برای Retrieve

PHP:
$firstBook = BookPeer::retrieveByPK(1);
// now $firstBook is a Book object, or NULL if no match was found.
حالا اگه شما چند Primary Key داشته باشید
PHP:
$selectedBooks = BookPeer::retrieveByPKs(array(1,2,3,4,5,6,7));

برای Update

PHP:
// 1) Fetch an object by primary key

$myBook = BookPeer::retrieveByPK(1);

// 2) update the values & save() it.

$myBook ->setTitle("War & Peace");
$myBook->save();

برای DELETE
PHP:
$book = BookPeer::retrieveByPK(1);
BookPeer::doDelete($book);

خب حتما پیش خودتون می گید من چطوری کوئری دلخواه خودمو بزنم ؟ راهشش Criteriaهست.
به عنوان مثال
PHP:
$c = new Criteria();
$c->add(AuthorPeer::FIRST_NAME, "Karl");
$c->add(AuthorPeer::LAST_NAME, "Marx", Criteria::NOT_EQUAL);

$authors = AuthorPeer::doSelect($c);
این دستور SQL رو اجرا می کنه
کد:
SELECT ... FROM author WHERE author.FIRST_NAME = 'Karl' AND author.LAST_NAME <> 'Marx';

البته Criteria خیلی پیچیده تر از این کد سادست که دیدید.
حالا شاید شما خواستید که یک دستور SQL رو وارد کنید باید چیکار کنید ؟
PHP:
<?php

$con = Propel::getConnection(DATABASE_NAME);

$sql = "SELECT books.* FROM books WHERE NOT EXISTS (SELECT id FROM review WHERE book_id = book.id)";  
$stmt = $con->createStatement();
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_NUM);  

$books = BookPeer::populateObjects($rs);

همونطور که می بینید تمامی امکانات مورد نیاز برای زدن کوئری در اختیار شما هست.

پیشنهاد می کنم حتما یک بار تجربه کنید ، احتمال زیادی می دم که شما هم مثل من مجذوب قدرت و امنیت این فریم ورک می شید.

موفق و پیروز باشید
 

جدیدترین ارسال ها

بالا