PHP Taking advantage of Traits and Doctrine2 for less lines of code

I did this app a time ago (~1 year) with Doctrine2+Symfony2 with simple Entities basically I was mimicking an excel sheet copying the values from the sheet to the database and setting all up for web usage.

The main Class was Item, this had Sub Entities Location, Protocol, State, etc…

These named here Location, Protocol, State had the same properties (fields), they also had to have a incrementable “Code” field witch, this was a basic copy paste to fill the tables and increment the number. Didn’t want to write the code to the different Entities so I used a Trait in a very lazy way I declared

TautoFill

namespace Far\AssetManagerBundle\Entity;

trait TautoFill {

    public function getAndInsert($val)
    {
        $this->_em->getConnection()->beginTransaction();

        $valtmp = strtoupper(str_replace(' ','',trim($val)));
        $Res = $this->findBy(['code' => $valtmp]);
        if (count($Res) > 0 && $Res[0] != null) {
            $obj = $Res[0];
            $obj->setTcount($obj->getTcount()+1);
            $this->_em->persist($obj);

            $this->_em->flush();

        } else {
            $tmp = $this->getClassName();
            $obj = new $tmp();
            $obj->setDescription($val);
            $obj->setCode($valtmp);
            $obj->setTcount(1);
            // persist
            $this->_em->persist($obj);
            $this->_em->flush();
        }

        $this->_em->getConnection()->commit();
        return $obj;
    }
}

So in a easy use TautoFill I got the data auto inserted and related to the main Item, without much work. Using a trait made the code more dynamic and easier to reimplement in the different situations without compromising hierarchy of the Entities.

Sobre Fernando André
SysAdmin, Website and Application Developer

Deixe uma Resposta

Please log in using one of these methods to post your comment:

Logótipo da WordPress.com

Está a comentar usando a sua conta WordPress.com Terminar Sessão / Alterar )

Imagem do Twitter

Está a comentar usando a sua conta Twitter Terminar Sessão / Alterar )

Facebook photo

Está a comentar usando a sua conta Facebook Terminar Sessão / Alterar )

Google+ photo

Está a comentar usando a sua conta Google+ Terminar Sessão / Alterar )

Connecting to %s

%d bloggers like this: