<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Un ciò voglia di dormì stanotte: Mo beccateve sto ORM va]]></title><description><![CDATA[<p dir="auto">Asd ... cosa vuol dire ORM ?</p>
<p dir="auto">ObjectRelationMapping ovvero Mappatura delle Relazioni tra gli Oggetti.</p>
<p dir="auto">Senza stare troppo a sottilizzare sul fatto che ogni database ha un linguaggio a se stante (bella rottura di beep beep .. autocensura) possiamo mappare gli oggetti che arrivano da una form con i campi del database in modo da non smaronarci più di tanto dato che le operazioni CRUD sono sempre 4 e di solito 1 non si attua in questa forma. CRUD = Create, Read, Update, Delete e solitamente quando si lavora su un database succede che:</p>
<ol>
<li>Quando vengono inseriti dei dati si ha un C=Create</li>
<li>Quando si aggiornano dei dati si ha un U=Update</li>
<li>Quando si cancellano dei dati si ha un D=Delete che solitamente avviene a metodo esterno (nomeOggetto-&gt;delete(IDDaDeletareComprensivoDiTuttoQuelloCheLoRiguarda))</li>
</ol>
<p dir="auto">Mentre l'R (Read) solitamente avviene mediante query che poi vengono più o meno artisticamente impaginate. Ergo una buona classe ORM deve contenere solamente 2 metodi + 1 che marca i dati per la cancellazione.</p>
<p dir="auto">La classe in questione (la terza C o i ragazzi del muretto si vi aggrada) si chiama DataBoudObject e non è niente di eccezionale. Semplicemente si appoggia su una sua figlia (class AggiungiRecord extends DataBoundObject) per ciò che concerne le relazioni tra i campi della form e quelli del database oltre a costruirsi le query da sola.</p>
<p dir="auto">Ok mo vediamo come va:</p>
<pre><code class="language-php">&lt;?php

abstract class DataBoundObject
{

    protected $ID;
    protected $objPDO;
    protected $strTableName;
    protected $arRelationMap;
    protected $blForDeletion;
    protected $blIsLoaded;
    protected $arModifiedRelation;
    
    abstract protected function DefinedTableName();
    abstract protected function DefineRelationMap();
    
    public function __construct(PDO $objPDO, $id = null)
    {
    
        $this-&gt;strTableName     = $this-&gt;DefineTableName();
        $this-&gt;arRelationMap     = $this-&gt;DefineRelationMap();
        $this-&gt;objPDO             = $objPDO;
        $this-&gt;blIsLoaded        = false;
        if (isset($id))
        {
            $this-&gt;ID = $id;
        }
        $this-&gt;arModifiedRelations = array;
        
    }
    
    public function Load()
    {
    
        if (isset($this-&gt;ID))
        {
            $strQuery = "SELECT ";
            foreach ($this-&gt;arRelationMap as $key =&gt; $value)
            {
                $strQuery .= "\"" . $key . "\",";
            }
            $strQuery = substr($strQuery, 0, strlen($strQuery) -1 );
            $strQuery .= " FROM " . $this-&gt;strTableName . " WHERE \"id\" = :eid";
            $objStatement = $this-&gt;objPDO-&gt;prepare($strQuery);
            $objStatement-&gt;bindParam(':eid', $this-&gt;ID, PDO::PARAM_INT);
            $objStatement-&gt;execute();
            $arRow = $objStatement-&gt;fetch(PDO::FETCH_ASSOC);
            foreach ($arRow as $key =&gt; $value)
            {
                $strMember = $this-&gt;arRelationMap[$key];
                if (property_exists($this, $strMember))
                {
                    if (is_numeric($value))
                    {
                        eval('$this-&gt;' . $strMember . ' = ' . $value . ';');
                    } else {
                        eval('$this-&gt;' . $strMember . ' = "' . $value . '";');
                    }
                }
            }
        $this-&gt;blIsLoaded = true;
    }
    
    public function Save()
    {
        if (isset($this-&gt;ID))
        {
            $strQuery = 'UPDATE "' . $this-&gt;strTableName . '" SET ';
                foreach ($this-&gt;arRelationMap as $key =&gt; $value)
                {
                    eval ('$actualVal = &amp;$this-&gt;' . $value . ';');
                    if (array_key_exists($value, $this-&gt;arModifiedRelations))
                    {
                        $strQuery .= '"' . $key . "\" = :$value, ";
                    }
                }
            $strQuery = substr($strQuery, 0, strlen($strQuery) -2);
            $strQuery .= ' WHERE "id" = :eid';
            unset($objPDOStatement);
            $objStatement = $this-&gt;ObjPDO-&gt;prepare($strQuery);
            $objStatement-&gt;bindValue(':eid', $this-&gt;ID, PDO::PARAM_INT);
                foreach ($this-&gt;arRelationMap as $key =&gt; $value)
                {
                    eval('$actualVal = &amp;$this-&gt;' . $value . ';');
                    if (array_key_exists($value, $this-&gt;arModifiedRelations))
                    {
                        if ((is_int($actualVal) || ($actualVal == null))
                        {
                            $objStatement-&gt;bindValue(':' . $value, $actualVal, PDO::PARAM_STR);
                        }
                    }
                }
            $objStatement-&gt;execute();
        } else {
            $strValueList = "";
            $strQuery = 'INSERT INTO "' . $this-&gt;strTableName . '"(';
            foreach ($this-&gt;arRelationMap as $key =&gt; $value)
            {
                eval('$actualVal = &amp;$this-&gt;' . $value . ';');
                if (isset($actualVal))
                {
                    if (array_key_exists($value, $this-&gt;arModifiedRelation))
                    {
                        $strQuery .= '"' . $key . '", ';
                        $strValueList .= ":$valuem ";
                    }
                }
            }
            $strQuery = substr($strQuery, 0, strlen($strQuery) -2);
            $strValueList = substr($strValueList, 0, strlen($strVaueList) -2);
            $strQuery .= ") VALUES (";
            $strQuery .= $strValueList;
            $strQuery .= ")";
            unset ($objStatement);
            $objStatement = $this-&gt;objPDO-&gt;prepare($strQuery);
            foreach ( $this-&gt;arRelationMap as $key =&gt; $value)
            {            
                eval('$actualVal = &amp;$this-&gt;' . $value . ';');
                if (isset($actualVal))
                {
                    if (array_key_exists($value, $this-&gt;arModifiedRelations))
                    {
                        if ((is_int($actualVal) || ($actualVal == null))
                        {
                            $objStatement-&gt;bindValue(':' . $value, $actualVal, PDO::PARAM_STR);
                        ]
                    }
                }
            }
            $objStatement-&gt;execute();
            $this-&gt;ID = $this-&gt;objPDO-&gt;LastInsertId($this-&gt;strTableName . "_id_seq");
        }    
    }
    
    public function MarkForDeletion()
    {
        $this-&gt;blForDeletion = true;
    }
    
    public function __destruct()
    {
        if (isset($this-&gt;ID))
        {
            if ($this-&gt;blForDeletion == true)
            {
                $strQuery = 'DELETE FROM "' . $this-&gt;strTableName . '" WHERE "id" = :eid';
                $objStatement = $this-&gt;objPDO-&gt;prepare($strQuery);
                $objStatement-&gt;bindValue(':eid', $this-&gt;ID, PDO::PARAM_INT);
                $objStatement-&gt;execute();
            }
        ]
    ]
    
    public function __call($strFunction, $arArguments)
    {
        $strMethodType = substr($strFunction, 0 ,3);
        $strMethodMember = substr($strFunction, 3);
        switch ($strMethodType)
        {
            case "set":
                return ($this-&gt;SetAccessor($strMethodMember, $arArguments[0]));
                break;
                
            case "get":
                return ($this-&gt;GetAccessor($strMethodMember));
                break;
        }
        return false;
        
    }
    
    private function setAccessor($strMember, $strNewValue)
    {
        if (property_exists($this, $strMember))
        {
            if (is_numeric($strNewValue))
            {
                eval ('$this-&gt;' . $strMember . ' = ' . $strNewValue . ';');
            } else {
                eval ('$this-&gt;' . $strMember . ' = "' . $strNewValue . '";');
            }
            $this-&gt;arModifieldRelations[$strMember] = "1";
        } else {
            return false;
        }
    }
    
    private function GetAccessor($strMember))
    {
        if ($this-&gt;blIsLoaded != true)
        {
            $this-&gt;Load();
        }
        if (property_exists($this, $strMember)
        {
            eval ('$strRetVal = $this-&gt;' . $strMember . ';');
            return $strRetVal;
        } else {
            return false; 
        }
    }
    
}
</code></pre>
<p dir="auto">Ok mo che abbiamo fatto ? Nulla di che. Solamente definito una classe astratta che a sua volta definisce, ma non implementa, due metodi astratti che ci permetteranno di gestire il database oltre al fatto che i metodi Load e Save le query se le fanno da soli <img src="https://dev.connect.gt/assets/plugins/nodebb-plugin-emoji/emoji/android/1f642.png?v=12b9555a9a1" class="not-responsive emoji emoji-android emoji--slightly_smiling_face" style="height:1.4em;width:auto;vertical-align:middle" title=":)" alt="🙂" /></p>
<p dir="auto">Il motivo per cui si ridefiniscono i metodi astratti è semplice. Supponiamo che voglia immettere nel mio database i seguenti dati relativi a un utente: Nome, Cognome, Username, Password, Mail, Avatar e che il mio collega pinco pallo voglia mettrci gli stessi miei ma con in più Indirizzo reale, cap, comune, città, numero di cellulare.</p>
<p dir="auto">A questo punto possiamo usare tutti e due la stessa classe solo che io definirò una sottoclasse come la seguente, lui una con alcuni campi in più.</p>
<pre><code class="language-php">class User extends DataBoundObject
{

    protected $FirstName;
    protected $LastName;
    protected $Username; 
    protected $Password;
    protected $EmailAddress;
    protected $DataLastLogin;
    protected $TimeLastLogin;
    protected $DataAccountCreated;
    protected $TimeAccountCreated;
    
    protected function DefineTableName()
    {
        return "User";
    }
    
    protected function DefineRelationMap()
    {
        return array(
                        "id"                     =&gt; "ID",
                        "firstName"             =&gt; "FirstName",
                        "lastName"             =&gt; "LastName",
                        "username"                 =&gt; "Username",
                        "md5Pw"                 =&gt; "Password",
                        "emailAddress"         =&gt; "EmailAddress",
                        "dateLastLogin"        =&gt; "DateLastLogin",
                        "timeLastLogin"        =&gt; "TimeLastLogin",
                        "dateAccountCreated"    =&gt; "DateAccountCreated",
                        "timeAccountCreated"    =&gt; "TimeAccountCreated"
                    );
    }
    
}
</code></pre>
<p dir="auto">Come si nota estendendo la classe principale implemento due metodi.</p>
<p dir="auto">Il primo indica al motore del database su che tabella lavorare<br />
Il secondo su quali campi.</p>
<p dir="auto">Si potrebbe estendere la classe principale anche in questo modo:</p>
<pre><code class="language-php">class Product extends DataBoundObject
{

    protected $ProductName;
    protected $ProductDescription;
    protected $ProductQuantity; 
    protected $ProductPrice;
    protected $ProductImage;

    protected function DefineTableName()
    {
        return "Product";
    }
    
    protected function DefineRelationMap()
    {
        return array(
                        "id"                     =&gt; "ID",
                        "productName"             =&gt; "ProductName",
                        "productDescription"             =&gt; "ProductDescription",
                        "productQantity"                 =&gt; "ProductQuantity",
                        "productPrice"                 =&gt; "ProductPrice",
                        "productImage"         =&gt; "ProductImage"
                    );
    }
    
}
</code></pre>
<p dir="auto">Ovviamente in entrambi i casi bisogna che si conoscano i veri campi nel database. In questi esempi ho usato le mie nomenclature</p>
]]></description><link>https://dev.connect.gt/topic/175615/un-ciò-voglia-di-dormì-stanotte-mo-beccateve-sto-orm-va</link><generator>RSS for Node</generator><lastBuildDate>Wed, 25 Nov 2026 20:58:20 GMT</lastBuildDate><atom:link href="https://dev.connect.gt/topic/175615.rss" rel="self" type="application/rss+xml"/><pubDate>Wed, 15 Aug 2012 01:22:10 GMT</pubDate><ttl>60</ttl></channel></rss>