De C# a php

Después de muchos años programando en C# la vida me a llevado a desarrollar con php.

Después de resistirme y menospreciar este lenguaje ahora puedo decir con orgullo que es mi favorito.

En el tiempo que he trabajado con php he construido algunas clases que me han ayudado a agilizar mi trabajo. Voy a dejar el código y la forma de usarse por si alguien está interesado en usarlas.

Vamos a usar tres clases para construir un ComboBox enlazado a una base datos MySql. Los archivos se llamarán Connection.php, DataAccess.php y ComboBox.php. Después publicaré las Clases DataTable y ListBox tambien enlazados a una base de datos MySql.

Clase ComboBox

<?php

/**
 * Description of ComboBox
 *
 * @author rgonzalez
 */
class ComboBox
{

    //Propiedades

    private $id = '';
    private $name = '';
    private $style = '';
    private $class = '';
    private $datavaluefield = '';
    private $datatextfield = '';
    private $datasource = array();
    private $selected = false;
    private $itemselected = '0';
    private $onblur = '';
    private $onchange = '';
    private $onfocus = '';
    private $onselect = '';
    private $onclick = '';
    private $onsubmit = '';
    private $disabled = false;
    private $addrowfirst = '';
    private $wraphtmlcode = '';
    private $labelname = '';

    public function SetID($id_)
    {
        $this->id = $id_;
    }

    public function SetName($name_)
    {
        $this->name = $name_;
    }

    public function SetStyle($style_)
    {
        $this->style = $style_;
    }

    public function SetClass($class_)
    {
        $this->class = $class_;
    }

    public function SetDataValueField($valsource_)
    {
        $this->datavaluefield = $valsource_;
    }

    public function SetDataTextField($textsource_)
    {
        $this->datatextfield = $textsource_;
    }

    public function SetDataSource($arraysource_)
    {
        $this->datasource = $arraysource_;
    }

    public function SetSelected($selected_)
    {
        $this->selected = $selected_;
    }

    public function SetItemSelected($itemselected_)
    {
        $this->itemselected = $itemselected_;
    }

    public function SetOnBlur($onblur_)
    {
        $this->onblur = $onblur_;
    }

    public function SetOnChange($onchange_)
    {
        $this->onchange = $onchange_;
    }

    public function SetOnFocus($onfocus_)
    {
        $this->onfocus = $onfocus_;
    }

    public function SetOnSelect($onselect_)
    {
        $this->onselect = $onselect_;
    }

    public function SetOnClick($onclick_)
    {
        $this->onclick = $onclick_;
    }

    public function SetOnSubmit($onsubmit_)
    {
        $this->onsubmit = $onsubmit_;
    }

    public function SetDisabled($disabled_)
    {
        $this->disabled = $disabled_;
    }

    public function SetAddRowFirst($addrowfirst_)
    {
        $this->addrowfirst = $addrowfirst_;
    }

    public function SetWrapHtmlCode($wraphtmlcode_)
    {
        if ($wraphtmlcode_ !== '') {
            $this->wraphtmlcode = $wraphtmlcode_;
        }
    }

    public function SetLabelName($labelname_)
    {
        if ($labelname_ !== '') {
            $this->labelname = $labelname_;
        }
    }

    public function CreateComboBox()
    {
        $disabled = '';
        if ($this->disabled === true) {
            $disabled = 'disabled';
        }

        $class = ($this->class === '') ? '' : 'class="' . $this->class . '"';
        $id = ($this->id === '') ? '' : 'id="' . $this->id . '"';
        $style = ($this->style === '') ? '' : 'style="' . $this->style . '"';
        $name = ($this->name === '') ? '' : 'name="' . $this->name . '"';
        $script = $this->StringFunctionsJavaScript();

        $IniSelect = <<<SEL
<select $id $class $style $name $disabled $script> 
SEL;

        $Options = '';
        $valfield = $this->datavaluefield;
        $textfield = $this->datatextfield;

        if ($this->addrowfirst === '') {
            $Options = '';
        } else {
            $Options = '<option value="0">' . $this->addrowfirst . '</option>';
        }

        $msgErr = $this->ValidateObject($this->datasource);
        if($msgErr !== '')
        {
            $Options = '<option selected value="0">.: Error :.</option>';
            $Options .= '<option value="1">.: ' . $msgErr . ' :.</option>';
            $FinSelect = '</select>';
            return $this->WrapInputInHtml($IniSelect . $Options . $FinSelect);
        }

        if ($this->datasource !== null) {

            if( isset($this->datasource[0]->code) )
            {
                $Options = '<option selected value="0">.: 0 rows matched :.</option>';
                $FinSelect = '</select>';
                return $this->WrapInputInHtml($IniSelect . $Options . $FinSelect);                
            }            
            foreach ($this->datasource as $key => $value) {
                if ($this->itemselected == $value->$valfield) {
                    $Options = $Options . '<option selected value="' . $value->$valfield . '">' . $value->$textfield . '</option>';
                } else {
                    $Options = $Options . '<option value="' . $value->$valfield . '">' . $value->$textfield . '</option>';
                }
            }
            $FinSelect = '</select>';
            return $this->WrapInputInHtml($IniSelect . $Options . $FinSelect);
        } else {
            $Options = '<option selected value="0">.: Connection or DataBase error :.</option>';
            $FinSelect = '</select>';
            return $this->WrapInputInHtml($IniSelect . $Options . $FinSelect);
        }
    }

    private function ValidateObject($object)
    {
        try
        {
            if (!isset($object[0])) {
                throw new Exception('DataSource Object is not valid...');
            } else {
                if (!is_object($object[0])) {
                    throw new Exception('DataSource Object is not valid...');
                }
            }
            return '';
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    private function WrapInputInHtml($strcombobox)
    {
        if ($this->wraphtmlcode === '') {
            return $strcombobox;
        } else {

            $newhtmlcode = str_replace("_INPUT_", $strcombobox, $this->wraphtmlcode);
            $newhtmlcode2 = str_replace("_ID_", $this->StrPull($this->id), $newhtmlcode);
            $newhtmlcode3 = str_replace("_LNAME_", $this->labelname, $newhtmlcode2);
            return $newhtmlcode3;
        }
    }

    private function StrPull($string_)
    {
        $pos1 = strpos($string_, "\"");
        $newstr = substr($string_, $pos1 + 1);
        $pos2 = strpos($newstr, "\"");
        $newstr2 = substr($string_, $pos1 + 1, $pos2);
        return $newstr2;
    }

    private function StringFunctionsJavaScript()
    {
        $eventosscript = '';

        if ($this->onblur !== '') {
            $eventosscript .= "onblur=\"$this->onblur\"";
        }
        if ($this->onchange !== '') {
            $eventosscript .= "onchange=\"$this->onchange\"";
        }
        if ($this->onfocus !== '') {
            $eventosscript .= "onfocus=\"$this->onfocus\"";
        }
        if ($this->onselect !== '') {
            $eventosscript .= "onselect=\"$this->onselect\"";
        }
        if ($this->onclick !== '') {
            $eventosscript .= "onclick=\"$this->onclick\"";
        }
        if ($this->onsubmit !== '') {
            $eventosscript .= "onsubmit=\"$this->onsubmit\"";
        }

        return $eventosscript;
    }

}

Clase Connection.php

<?php

/**
 * Description of class Connection
 *
 * @author rgonzalez
 */
class Connection
{
    private $db_host = '';
    private $db_database = '';
    private $db_user = '';
    private $db_password = '';

    public function __construct($db_host_, $db_database_, $db_user_, $db_password_)
    {
        $this->db_host = $db_host_;
        $this->db_database = $db_database_;
        $this->db_user = $db_user_;
        $this->db_password = $db_password_;
    }

    public function SimpleConnectionPDO()
    {
        try
        {
            $dsn = sprintf("mysql:host=%s;dbname=%s", $this->db_host, $this->db_database);
            $pdo = new PDO($dsn
                    , $this->db_user
                    , $this->db_password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->exec("SET NAMES utf8");

            return $object = array(
               'suc_' => true
               , 'obj_' => $pdo
               , 'msg_' => 'Successful connection.'
               , 'num_' => 0
               , 'det_' => sprintf("Connection dns: HOST:%s, DBNAME:%s, DBUSER: %s, DBPASS:*****", $this->db_host, $this->db_database, $this->db_user)
            );
        } catch (PDOException $Ex)
        {
            return $object = array(
               'suc_' => false
               , 'obj_' => array(0=>(object)array('id' => 1, 'code' => $Ex->getCode(), 'messege' => $Ex->getMessage()))
               , 'msg_' => $Ex->getMessage()
               , 'num_' => 0
               , 'det_' => $Ex->getFile() . " | Line: " . $Ex->getLine()
            );
        }
    }

    public function PersistentConnectionPDO()
    {
        try
        {
            $dsn = sprintf("mysql:host=%s;dbname=%s",  $this->db_host, $this->db_database);
            $pdo = new PDO($dsn
                    , $this->db_user
                    , $this->db_password
                    , array(PDO::ATTR_PERSISTENT => true));

            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->exec("set names latin1");

            return $valores = array(
               'suc_' => true
               , 'obj_' => $pdo
               , 'msg_' => 'Successful connection.'
               , 'num_' => 0
               , 'det_' => sprintf("Connection dns: HOST:%s, DBNAME:%s, DBUSER: %s, DBPASS:*****", $this->db_host, $this->db_database, $this->db_user)
            );
        } catch (PDOException $Ex)
        {
            return $valores = array(
               'suc_' => false
               , 'obj_' => array(0=>(object)array('id' => 1, 'code' => $Ex->getCode(), 'messege' => $Ex->getMessage()))
               , 'msg_' => $Ex->getMessage()
               , 'num_' => 0
               , 'det_' => $Ex->getFile() . " | Line: " . $Ex->getLine()
            );
        }
    }   
}

Clase DataAccess.php

<?php

/**
 * Description of class DataAccess
 *
 * @author rgonzalez
 */
class DataAccess
{
    private $respConn = null;
    private $params = '{":none":"none|string"}';
    private $querycmd = "";
    private $querycrud = "";

    public function ExecuteCommand()
    {
        $pars = $this->ValidateParams();
        if ($pars['suc_'] === false) {
            return $pars;
        }
        foreach ($this->CreateJsonEncode() as $key => $value) 
        {
            if ($key === 'params') {$ArrayParams = $value;} 
            else if ($key === 'vars') {$ArrayVar = $value;}
        }
        $StrQry = $ArrayVar->QueryString;
        try {

            $DatsJson = $this->ExecuteQry($ArrayParams, $StrQry, $ArrayVar);
            return $DatsJson;

        } catch (Exception $Ex) {

            $DatsJson = $this->MsgErrException($Ex);
            return $DatsJson;
        }
    }

    private function ValidateParams()
    {
        $json_valid = $this->CreateJsonEncode();
        if (is_null($json_valid)) {
            $values = array(
                'suc_' => false
                , 'obj_' => array(0 => (object) array('id' => 1, 'code' => 0, 'messege' => 'Error in json string...'))
                , 'msg_' => 'Error in json string. Something is wrong en json string, please validate...'
                , 'num_' => 0
                , 'det_' => "Error in json string. Something is wrong en json string, please validate...",
            );
            return $values;
        } 
        else 
        {

            $names = '';
            foreach ($this->CreateJsonEncode() as $key => $value) 
            {
                if ($key === 'params') {$names .= '1';} 
                else if ($key === 'vars') {$names .= '1';}
            }
            if($names !== '11')
            {
                $values = array(
                    'suc_' => false
                    , 'obj_' => array(0 => (object) array('id' => 1, 'code' => 0, 'messege' => 'Error in key(s) of json string...'))
                    , 'msg_' => 'Error in keys of json string.'
                    , 'num_' => 0
                    , 'det_' => 'Error in keys of json string. Example: {"params":{":param1":1},"vars":{"TypeFuncion":"Read",QueryString":"SELECT field1, field2 FROM table1 WHERE field3 = :param1;"}}',
                );
                return $values;
            }

            $values = array(
                'suc_' => true
                , 'obj_' => array(0 => (object) array('id' => 1, 'code' => 1, 'messege' => 'Valid json string'))
                , 'msg_' => 'Parameters ok. Valid json string...'
                , 'num_' => 1
                , 'det_' => "Success parameters!",
            );
            return $values;
        }
    }

    private function ExecuteQry($ArrayParams, $StrSP, $ArrayVar)
    {
        $Statement = $this->respConn->prepare($StrSP);
        $i = 1;

        if(strpos($StrSP, '?'))
        {
            foreach ($ArrayParams as $value) {
                $vals = explode('|',$value);
                $type = $this->TipoDat($vals);                
                $Statement->bindValue($i, $type[0], $type[1]);
                $i++;
            }
        }
        else
        {
            foreach ($ArrayParams as $key => $value) {
                $vals = explode('|',$value);
                $type = $this->TipoDat($vals);
                $Statement->bindParam($key, $type[0], $type[1]);
            }
        }

        $result = $Statement->execute();

        if ($result === true) {

            $NumRows = $Statement->rowCount();
            
            if($ArrayVar->TypeFuncion === 'Read')
            {
                $Table = $Statement->fetchAll(\PDO::FETCH_OBJ);
            }
            else if($ArrayVar->TypeFuncion === 'Insert')
            {
                $last_id = $this->respConn->lastInsertId();
                $Table = array(0 => (object) array('id' => 1, 'code' => $last_id, 'messege' => 'Row id inserted: ' . $last_id ));
            }
            else if($ArrayVar->TypeFuncion === 'Update')
            {
                $last_id = $this->respConn->lastInsertId();
                $Table = array(0 => (object) array('id' => 1, 'code' => $last_id, 'messege' => 'Row updated' ));
            }            
            else if($ArrayVar->TypeFuncion === 'Delete')
            {
                $last_id = $this->respConn->lastInsertId();
                $Table = array(0 => (object) array('id' => 1, 'code' => $last_id, 'messege' => 'Row deleted' ));
            }            
            else
            {
                $Table = array(0 => (object) array('id' => 1, 'code' => 1, 'messege' => 'Affected rows matched: ' . $NumRows ));
            }
            
            if ($NumRows === 0) {
                $Table = array(0 => (object) array('id' => 1, 'code' => 0, 'messege' => 'Affected rows matched: ' . $NumRows ));
            }
            
            $values = array('suc_' => true
                , 'obj_' => $Table
                , 'msg_' => 'Success'
                , 'num_' => $NumRows
                , 'det_' => "Stored Procedure or Query is ok. Affected rows matched: " . $NumRows . ' || ' . $StrSP);
            $DatsJson = $values;
            return $DatsJson;
        } else {
            $values = array('suc_' => false
                , 'obj_' => $result
                , 'msg_' => 'Error'
                , 'num_' => 0
                , 'det_' => "Stored Procedure or Query width errors." . ' || ' . $StrSP);
            $DatsJson = $values;
            return $DatsJson;
        }
    }

    private function TipoDat($dat)
    {
        if($dat[1] === 'string')
        {
            return array($dat[0],PDO::PARAM_STR);
        }
        else if($dat[1] === 'int')
        {
            return array((int)$dat[0],PDO::PARAM_STR);
        }
        else if($dat[1] === 'bool')
        {
            return array((bool)$dat[0],PDO::PARAM_STR);
        }
    }

    private function MsgErrException($Ex)
    {
        $values = array(
            'suc_' => false
            , 'obj_' => array(0 => (object) array('id' => 1, 'code' => $Ex->getCode(), 'messege' => $Ex->getMessage()))
            , 'msg_' => $Ex->getMessage()
            , 'num_' => (int) $Ex->getCode()
            , 'det_' => $Ex->getFile() . " | Line: " . $Ex->getLine(),
        );
        $DatsJson = $values;
        return $DatsJson;
    }

    private function CreateJsonEncode()
    {
        $JsonParams = '{"params":' . $this->params . ',
                "vars":{"TypeFuncion":"' . $this->querycmd . '","QueryString":"' . $this->querycrud . '"}}';
        
        return json_decode($JsonParams);
    }

    /**
     *
     * @param type object PDO connection. The control Conecction.php return a object with the object connection.
     *     $obj_cn = new Connection('localhost', 'mydatabase', 'root', '');
     *     $conn = $obj_cn->SimpleConnectionPDO();
     *     $qry = new DataAccess();
     *     $qry->SetConn($conn['obj_']);
     */
    public function SetConn($respConn_)
    {
        $this->respConn = $respConn_;
    }

    /**
     * Set the value of params
     *
     * @return  self
     */ 
    public function setParams($params)
    {
        $this->params = json_encode($params);
        return $this;
    }

    /**
     * Set the value of querycmd
     *
     * @return  self5
     */ 
    public function setQuerycmd($querycmd)
    {
        $this->querycmd = $querycmd;

        return $this;
    }

    /**
     * Set the value of querycrud
     *
     * @return  self
     */ 
    public function setQuerycrud($querycrud)
    {
        $this->querycrud = $querycrud;

        return $this;
    }
}

Uso de las clases

Parece complicado tanto código pero una vez que los copias y los guardas en archivos php lo demás ya es pan comido.

<?php
// debes de poner el path dónde colocaste los archivos o clases.
require_once 'Connection.php';
require_once 'DataAccess.php';
require_once 'ComboBox.php';

// Abrir la conexión
// Crear una instancia de la conexión
$conn = new Connection('localhost', 'BaseDatos', 'Usuario', 'Contraseña');
//Creamos la conexión. La función crea un array.
$link = $conn->SimpleConnectionPDO();

// Creamos la instancia de la clase DataAccess
$exec = new DataAccess();

// Le pasamos el array con la clave ['obj_'] de la conexión.  
$exec->SetConn($link['obj_']);

// Le pasamos el tipo de consulta.
$exec->setQuerycmd("Read");
$exec->setQuerycrud("SELECT id, val1, val2, val3 FROM pruebas;");
// La siguiente función crea un array con el objeto de los datos que le pasaremos al ComboBox
$dats = $exec->ExecuteCommand();

// Le pasamos el array con la clave ['obj_'] de donde viene los datos. 
$cb->SetDataSource($dats['obj_']);
$cb->SetDataValueField('id');  // Campo que toma como valor del Option Select HTML
$cb->SetDataTextField('val1'); // Campo que toma como Texto del Option Select HTML
$cb->SetItemSelected('2'); // Valor que se quiere selccionar
$cb->SetID('cmbSmartphones'); // #id del SELECT HTML que genera
$cb->SetName('cmbSmartphones'); // name del SELECT HTML
$cb->SetClass('Combo'); // Clase css que quiere pasarse al SELECT
$cb->SetStyle('font-size:20px; width:245px;'); // Estilo css
$cb->SetOnChange("Alerts()"); // función javascript que se quiere pasar al SELECT HTML


echo '<script> function Alerts() { console.log("ComboBox it changed. Value: " + document.getElementById("cmbSmartphones").value + "."); }</script>';
echo $cb->CreateComboBox();

Bueno esto es muy útil por que todo el código se genera en PHP lo que hace que se vea mas limpio el HTML.

Cualquier duda estaré contestando sus comentarios.

Publicado por jazdian

Desarrollador web freelancer

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s

A %d blogueros les gusta esto: