Git Product home page Git Product logo

leanmapper's People

Contributors

castamir avatar cniry avatar codelingobot avatar dakujem avatar enumag avatar greeny avatar janpecha avatar leninzprahy avatar martyix avatar mibk avatar pmachan avatar radmax avatar tharos avatar uestla avatar vojir avatar vojtech-dobes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

leanmapper's Issues

PostgreSQL vyhazuje chybu při $entity->removeFromX($atr);

Při zavolání metody removeFromX() na entitě vygeneruje Lean Mapper u M:N vazeb tento dotaz:

DELETE 
FROM "prvni_druha" 
WHERE "prvni_id" = 101 AND "druha_id" = 2 
LIMIT 1

Postgre ale nevezme ten LIMIT a vyhodí chybu syntax error at or near "LIMIT". Bez limitu stejný dotaz provede.

Entity: getting id after persisting fails (single table inheritance only)

I have updated LM to the latest dev version (a38b838) and my tests started to fail. I'm trying to get id of just persisted entity (occurs only for entities using single table inheritance)

Usage:

$company = new Company();
$company->field = "Value";
$userRepo->persist($company);

echo $company->userId; // Missing 'user_id' value for requested row.

My mapper for STI:

public function getEntityClass($table, \LeanMapper\Row $row = NULL) {        
  if ($table === 'user' && $row !== null) {
      switch ($row->subject) {
          case User::SUBJECT_COMPANY: $table = 'company'; break;
          case User::SUBJECT_PERSON: $table = 'person'; break;
      }
  }

  return parent::getEntityClass($table, $row);
}

public function getEntityField($table, $column) {     

  if($table === "company" || $table === "person") {
    $table = "user";
    $column = str_replace(array("company", "person"), "user", $column);
  }

  return parent::getEntityField($table, $column);
}

I was slightly checking the changes, but I didn't find the bug. My previous version was 2.0.1

BelongsToMany přes dva sloupce

Zdravím,
mám entitu Node (id, label) a Edge (id, source, target, label). Edge reprezentuje vazbu mezi dvěma Node.

V Node chci metodu getEdges(), která mi vrátí Edge[] seřazené dle mých kritérií.

Dotaz pro konkrétní Node s id 1 by vypadal takto:

SELECT * FROM edge WHERE source = 1 OR target = 1 ORDER BY label

Zároveň nechci přijít o NotORM princip. Jak toto prosím v LeanMapperu řešit?
Děkuji

Add support for non-strict SQL mode

If I'm not using SQL strict mode (neither STRICT_TRANS_TABLES nor STRICT_ALL_TABLES), following code will fail:

/**
 * @property-read int                         $addressId
 * @property      string                      $city
 */
class Address extends BaseEntity {}

//////
$address = new Address();
$this->addressRepo->persist($address);
echo $address->city; // Cannot get value of property 'city' in entity Model\Entity\Partner due to low-level failure: missing 'city' column in row with id X

I know that non-strict SQL mode could be dangerous. I'm using it just in tests, because filling all properties in all test entities makes the tests very long and unreadable.

So the question is: can you add support for this or is there any workaround for me?

I've been using this in 2.0.1 version of LeanMapper without any problems. Now, I've updated to 2.1 and my tests are failing :)

Multi-persist (aneb Am I Doing It Right?)

Mám návrh na zlepšení metody persist() pro podporu persistence více entit najednou. Zároveň je to taky dotaz, zda se to takhle dá používat a jestli by k tomu nebylo dobré poupravit i metodu persistHasManyChanges(), protože v tomto případě pokládá co entita to insert do vazební tabulky.

public function persist($entities)
{
    /** @var Entity[] $entities */
    $entities = is_array($entities) ? $entities : array($entities);
    $entitiesToInsert = $entitiesToUpdate = array();

    $this->events->invokeCallbacks(Events::EVENT_BEFORE_PERSIST, $entities);

    foreach ($entities as $entity) {
        $this->checkEntityType($entity);
        if ($entity->isDetached()) {
            $entity->makeAlive($this->entityFactory, $this->connection, $this->mapper);
            $this->events->invokeCallbacks(Events::EVENT_BEFORE_CREATE, $entity);
            $entitiesToInsert[] = $entity;
        } elseif ($entity->isModified()) {
            $this->events->invokeCallbacks(Events::EVENT_BEFORE_UPDATE, $entity);
            $entitiesToUpdate[] = $entity;
        }

        $this->persistHasManyChanges($entity);
    }

    if (!(count($entitiesToInsert) || count($entitiesToUpdate))) return false;

    // insert new entities
    if ($entitiesToInsert) {
        $insertResult = $insertedIds = $this->insertRowsIntoDatabase($entitiesToInsert);
        foreach ($insertedIds as $key => $id) {
            $entitiesToInsert[$key]->attach($id);
            $this->events->invokeCallbacks(Events::EVENT_AFTER_CREATE, $entitiesToInsert[$key]);
        }
    }

    // update existing entities
    if ($entitiesToUpdate) {
        $updateResult = $this->updateRowsInDatabase($entitiesToUpdate);
        foreach ($entitiesToUpdate as $entity) {
            $entity->markAsUpdated();
            $this->events->invokeCallbacks(Events::EVENT_AFTER_UPDATE, $entity);
        }
    }

    $this->events->invokeCallbacks(Events::EVENT_AFTER_PERSIST, $entities);

    return (isset($insertResult) && $insertResult) || (isset($updateResult) && $updateResult);
}

K tomu ještě metody insertRowsIntoDatabase()...

protected function insertRowsIntoDatabase(array $entities)
{
    $values = array();
    $primaryKey = $this->mapper->getPrimaryKey($this->getTable());
    foreach ($entities as $entity) {
        if (!($entity instanceof Entity) or !$entity->isDetached()) {
            throw new ApplicationException('Invalid set of entities given.');
        }
        $values[] = $entity->getModifiedRowData();
    }
    $this->connection->query('INSERT INTO %n %ex', $this->getTable(), $values);

    $startId = isset($values[0][$primaryKey]) ? $values[0][$primaryKey] : $this->connection->getInsertId();
    return range($startId, $startId + ($this->connection->affectedRows() - 1), 1);
}

... a updateRowsInDatabase()
vím že pokládat např. 35x query s UPDATE není moc košér, ale UPDATE s použitím CASE .. THEN (nebo u MySQL IF) není moc rychlejší.

protected function updateRowsInDatabase(array $entities)
{
    $primaryKey = $this->mapper->getPrimaryKey($this->getTable());
    $idField = $this->mapper->getEntityField($this->getTable(), $primaryKey);

    foreach ($entities as $entity) {
        if (!($entity instanceof Entity) or $entity->isDetached()) {
            throw new ApplicationException('Invalid set of entities given.');
        }
        if (!$this->connection->query('UPDATE %n SET %a WHERE %n = ?', $this->getTable(), $entity->getModifiedRowData(), $primaryKey, $entity->$idField))
            return false;
    }

    return true;
}

Jak efektivně na hromadné operace?

Ahoj,

mám entity account a subscription. Definované (zjednodušeno) takto:

/**
 * @property int $id
 * @property string $name
 */
class Account extends \LeanMapper\Entity
{

}

/**
 * @property int $id
 * @property DateTime $date_added
 * @property Account $account m:hasOne(account_id:account)
 */
class Subscription extends \LeanMapper\Entity
{
}

Nyní si představte, že potřebuji zpracovat například tisíc (prostě nějaké nezanedbatelné číslo) subscriptions a vždy budu potřebovat sáhnout na $subscription->account. V PHP tedy:

foreach ($subscriptions as $subscription) {

      // Následující řádka bude odpovídat spuštění SQL dotazu. Dohromady tato řádka tedy 
      // spustí 1000 SQL dotazů, že? Mohu tento počet dotazů snížit?
      $account = $subscription->account;  

      $result = doSomeWork($subscription);
      logOperation($account,  $subscription, $result);
      ...
}

Jak se toto řeší v LeanMapperu? Jediné, co mě napadá je, že si můžu napsat vlastní dotaz v Dibi a LeanMapper do problému vůbec netahat.

Díky

Typo: Property.php:102

Property '$name' with HasOney or BelongsToOne in entity {$entityReflection->getName()} relationship cannot contain collection.

HasOney -> HasOne? :)

Referencing last entity from set of entities

Lets say I have addresses connected to each other somehow (based on the distance or something) and look at this example:

foreach($partner->users as $user){ // standard belongsToMany
     $user->address // standard hasOne
          ->closestAddress; // $closestAddress m:belongsToOne m:filter(closest)
}

where the filter for closest address is defined like this:

$statement->orderBy("distance DESC")
          ->limit(1); // because there are many addresses connected

This actually fails on Cannot get value of property due to low-level failure: property cannot be null. Thats because LeanMapper is creating query asking for a set of addresses and the fetched one by limit 1 doesn't have to be the one with correct address id:

SELECT `address`.* 
FROM `address` 
WHERE `address`.`address_whatever_connection_id` IN (1, 2, 3) 
ORDER BY distance DESC 
LIMIT 1

So, this is quite confusing behaviour because following code is working.

$user = $userRepo->getSingle(1);
$user->address->closestAddress

Is it possible to prevent this in LM or should I take care when creating such filters? Somehow like this:

$statement->where("address_whatever_connection_id = %i", $wiredAddress->addressId) // wired
          ->orderBy("distance DESC")
          ->limit(1); // because there are many addresses connected

I know this example probably not the best (I've thought that up right now because the real example where is happened was really complex), but I hope you get my point. Also sorry for the title of this issue, I really dont know how to name this problem :)

N:M vazba s dodatečnou informací

nm

Jak nejlépe se z entity Order dobrat k položce count v order_has_product ?

Pomocí m:hasMany si dokážu vylistovat zvlášť produkty a ceny ale nenapadá mě jak dostat count (není to Entita)

Potřeboval bych z entity Order dostat výslednou cenu produktu.

Missing backticks for table name

The function createTableSelection (https://github.com/Tharos/LeanMapper/blob/develop/LeanMapper/Result.php#L761) returns invalid SQL query if given table name contains a dash.

The problem is in line:

return $this->connection->select('%n.*', $table)->from($table);

I can make it work by changing the previous line to the following one:

return $this->connection->select('%n.*', $table)->from('[' . $table . ']');

Example:

$table = 'product-pricing'

Original generated query:

SELECT `product-pricing`.* 
FROM product-pricing 
WHERE `product-pricing`.`product_id` IN (1, 2, 3, 4, 5, 6)

Correct query:

SELECT `product-pricing`.* 
FROM `product-pricing` 
WHERE `product-pricing`.`product_id` IN (1, 2, 3, 4, 5, 6)

Language Entity

When i've Language Entity and i add annotation to another Entitiy for example Product:

/**

  • @Property int $id
  • @Property string $name
  • @Property Language $language m:hasOne(language_id)
    */
    class Product extends \LeanMapper\Entity
    {
    }

Not work, class Result find language key and not language_id.

While i change language param $language to $lang work perfect.

/**

  • @Property Language $lang m:hasOne(language_id)
    */

Při traverzování umožnit ad-hoc podstrčení instance LeanMapper\Filtering

Napadla mě jedna taková „ďábelská“ věc.

Pokud se nyní traverzuje mezi entitami přes položku nadefinovanou čistě pomocí anotace, vždy se spouštějí relevantní filtry. Hledají se nejprve implicitní (podle typu entity, ke které traverzujeme) a pak ty, které jsou zapsané v příznaku m:filter. Pokud nalezené filtry přijímají nějaké dynamické parametry, lze jim je předat při přístupu k položce „pomocí metody“ (typicky magické). Například $book->getAuthor($onlyActive = true).


Napadlo mě, že každé takové property s vazbou by mohlo být možné dynamicky podstrčit instanci Filtering, která by se v takovém případě použila namísto filtrů uvedených v m:filter (ve výsledku by se tedy použily implicitní filtry a ty z předané instance Filtering).

Význam by byl velký. Kvůli limitování nebo seřazení načítaných entit by se nemusely uvádět žádné filtry v definici položek:

$orderedBooks = $author->getBooks(new Filtering(function (Fluent $statement) use ($mapper) {
    $statement->orderBy($mapper->getColumn(Book::class, 'published'))->desc();
}));

Takto by se získala nějak seřazená kolekce knih s tím, že o pár řádek jinde v kódu by se mohla získávat seřazená třeba úplně jinak.

Co si o tom myslíte?

Anotace u entit

Bylo by fajn mít možnost i anotace u entit, nejen u properties.

m:passThru sa invokuje ja nespravnom misete

teraz sa to za urcitich podmienok invokuje v \LeanMapper\Entity::__get a \LeanMapper\Entity::__set lebo teraz ak zavolam

$value = $entity->someValueWithPassThru;
$value = $entity->someValueWithPassThru;

tak sa pass thru invokuje 2x

idealne by to bolo spravit tak ako som to popisoval v tomto Feature requeste:
http://forum.nette.org/cs/14592-lean-mapper-tenke-orm-nad-dibi?p=15#p111964

cize: akonahle sa data nacitaju z DB tak sa invokuje passThru a tesne pred tym ako sa data ukladaju do DB sa znova invokuje passThru a nie pri getteroch a setteroch

tato feature reisi aj tento issue: #18

Closure Table

Jak nejlépe řešit closure table v LM?

Struktura

model01

Jak navrhnout entitu (category) a repository pokud chceme dostat všechny vlastní knihy ale i také knihy všech podřazených kategorií?

Categories

- Root
  | -- A
  | -- B
  |    | -- C
  |    | -- D
  |
  | -- E

Požadovaný výsledek

Category Books Result
Root - 1,2,3,4,5,6,7,8
A 1 1
B 2,3 2,3,4,5,6,7
C 4,5,6 4,5,6
D 7 7
E 8 8

Dotaz: řazení přes vazební tabulku

Je nějaký vychytaný způsob, jak řešit situaci, kdy vypisuju informace z jedné tabulky (Knihy), která se mj. váže do jiné tabulky (Person) a já chci seřadit výpis právě podle položky ve vazební tabulce (např. dle jména autora knihy) aniž bych musel použít přímo query? Upozorňuju, že chci řadit i podle jiných kritérií (název knihy)...

předem dík za odpověď

Drobnosti…

  • Pokud je při volání Result::__construct předán $originKey = null, vygenerovat nějaký náhodný, aby se vyloučilo přepisování cache.
  • Doplnit metodu Row::getResult. Usnadnilo by to pár případů užití a není to vyloženě nebezpečné… (Ke Connection se z entity i nadále dostat záměrně nedá.)

Support for @entity annotation

Setting the @entity annotation for repositories is the easiest way of specifying the entity class when my entities are scattered across multiple repositories. Writing a custom mapper means updating it with every new entity/namespace, which is cumbersome. Is there any way of implementing this functionality?

Persistování již persistovaných m:n entit

Pokud přidám entitě nějaké hasMany entity a persistuji je,

$book->addToTags($tag);
$bookRepository->persist($book);

tak pokud persistuji znovu (např. z důvodu provedení nějakých dalších změn), Lean Mapper se znovu pokusí o přidání hasMany entit (tedy znovu o přidání stejných již persistovaných tagů ke knize). Nepamatuje si tedy, že je již persistoval.

Ako spravne pisat fluent?

Obcas sa mi stava ze potrebujem rucne napisat query / fluent kt. obsahuje join na inu tabulku. Ako spravne odkazovat na tie joinovacie tabulky? napisat priamo string nazvot_tabulky ?

Implicitní passThru

Jak již bylo diskutováno zde, nestálo by za to zvážit implicitní passThru?

Má předběžná představa:

// V mapperu...
public function getImplicitPassThru($propertyType, $entityClass);

Co myslíte?

Add support for cleaning entity referencingResultsCache

Currently it is not possible to "refresh" referencing cache inside entity from outside. It could be usefull for such use-cases:

/*
 * @property-read Payment[] $blockingPayments m:belongsToMany m:filter(blockingPayment)
 */
class User extends BaseEntity {

    public function isBlockedByPayment(){
        return !empty($this->blockingPayments);
    }
}

// usage
$wasBlocked = $user->isBlockedByPayment();

$payment->payed = TRUE;
$this->paymentRepo->persist($payment); // might change user's blocking status

$isBlocked = $user->isBlockedByPayment(); // problem: getting data from cache

if($wasBlocked && !$isBlocked) {
    // ublocking action
}

Originally posted in Nette Forum

Vícenásobné použití generického filtru

Pokud v entitě použiji zápis:

 * @property-read Expense[] $expensesOrdered m:belongsToMany m:filter(orderBy#price,orderBy#id)

... kde implementace filtru orderBy je:

function orderBy(Fluent $statement, $orderBy)
{
    $statement->orderBy($orderBy);
}

Vede to při přístupu k této property na SQL s ORDER klauzulí:

ORDER BY `id` , `id`

Pokud jedno ze dvou použití filtru orderBy nahradím jiným filtrem sortBy se stejnou implementací, tj.

 * @property-read Expense[] $expensesOrdered m:belongsToMany m:filter(orderBy#price,sortBy#id)

... problém zmizí a generuje to správné:

ORDER BY `price` , `id`

Zachovávání kolekce ID ve Fluent

Filtru je předána (mimo jiné) instance LeanMapper\Fluent, což je jen malinko přizpůsobené DibiFluent. Dotaz, který se vygeneruje, lze ve filtru v podstatě úplně „překopat“.

Jenomže kdybychom například odebrali WHERE klauzuli a chtěli bychom ji nahradit nějakou vylepšenou, přišli bychom o IDkča souvisejících entit, které nás zajímají (tu část restrikce IN (..., ..., ...)). Jediné místo, kde jsou ta IDčka v ten okamžik uložená, je totiž vnitřní stav instance Fluent.

Napadlo mě, že by instance Fluent ta IDčka mohla mít uložené ještě v nějaké privátní položce a bylo by je možné z ní číst. Tím by šlo třeba úplně zrekonstruovat IN část dotazu.

Co si o tom myslíte?

Ponechat len BaseRepository

Vzhladom na to ze planujes zaviast Query objekty #32 tak sa chcem spitat ci nepouvazujes nad ponechanim len BaseRepository, aby sme nemuseli pre kazdu entitu robit prazdne repositare

class FooRepository extends \LeanMapper\Repository
{
}

resp. kto chce moze si podedit repository pre konkretne entity (tak ako to je teraz, aby sme sa vyhli BC) ale nech to nieje povinne...

Podpora anotací přes více řádků

Líbilo by se mi, kdyby se definice libovolné property mohla rozprostírat přes více řádků.

Řekněme, že by výhledově existoval nějaký generátor databázového schéma také nějaká univerzální form factory. Řekněme, že oba tyto nástroje mají 90 % z toho, co potřebují ke své práci znát, už nyní v anotacích u entit. Ale třeba 10 % informací ke svému běhu jim chybí (schema tool by třeba mohl chtít vědět, jak ukládat boolean, factory na formulář by mohla chtít vědět, jakou pokročilou validaci u dané položky použít atp.).

Asi nejčistější by v takovém případě bylo mít těch 10 % doplňujících informací uložených někde samostatně (v nějaký konfiguračních souborech), ale pragmatické je mít i tyto informace v anotacích u Entity.

Anotace jsou teď velmi stručné a to mi maximálně vyhovuje. Pokud by měly narůst, líbilo by se mi, kdyby mohly být přes více řádků:

<?php

/**
 * @property Book[] $books
 *     m:hasOne
 *     m:filter(order#published)
 *
 * @property int $age
 *     m:form(unsigned, range: 1-99)
 *
 * @property string|null $website
 */
class Author extends Entity
{
}

Co si o tom myslíte?

Entity: Accessing nullable property of persisted entity

I'm not sure if following behaviour was intended to be, but it is a little bit confusing for me.

/**
 * @property int $userId
 * @property string $name
 * @property null|string $website
 */
class User extends BaseEntity {}

////////

$user = new User();
$user->name = "John Doe";
$userRepo->persist($user);
$user->website; // Exception: Missing 'website' value for requested row.

$user2 = $userRepo->getSingle($user->userId);
$user2->website; // returns NULL

I would expect completely the same behaviour for both attached entities! Not that the one created manually and persisted will behave in different way than the one taken from database and created by $repo->createEntity() method.

Vydání další verze

Kdy (+-) se bude vydávat další verze? Od vydání 2.1 už uběhl nějaký ten pátek a bylo provedeno docela dost změn.

Případně potřebuji poradit jak nastavit require abych do projetu dostal dev-develop. Zatím to řeším pomocí require-dev

{
    "require-dev" : {
        "tharos/leanmapper": "dev-develop"
    }
}

z důvodu nastavení "minimum-stability": "RC" to v "require" nevidí dev-develop at se snažím jak chci.
Strukturu mam následující: Lib(potrebuje LM) > Projekt

Entity: getData() order keys by whitelist definition

Method getData should order array keys by whitelist if some provided. It is useful when generating csv with header for example:

/**
 * @property string $name
 * @property string $surname
 */
class User extends BaseEntity {}

////

$header = array(
    "Surname",
    "Name",
);
$whitelist = array(
    "surname",
    "name",
);
$data = $user->getData($whitelist);
$csvGenerator->generate($data, $header); // inconsistent csv header

It is not such a big issue, but it can be handful in some cases :)

Pridat vlastne eventy

v BaseRepository mam metodu:

public function createNew()
{
    $className = $this->mapper->getEntityClass($this->getTable());
    /** @var $entity BaseEntity */
    $entity = new $className;

    $this->events->invokeCallbacks(Events::EVENT_FOO, $entity);

    return $entity;
}
  1. ide o to Events::EVENT_FOO rad by som si do eventov pridal vlastny typ eventu a invokoval ho ked potrebujem
  2. a tym padom ze to je v BaseRepository by som chcel mat ten event registrovany pre kazdy Repository preto by bolo super mat moznost pridat nejake zdielane eventy (napr do Events pridat nejake staticke pole kde budu tie zdielane eventy)

Otazka: o kolko je LM rychlejsi ako Doctrine 2 ?

Zdravim, robil niekto porovania LM vs Doctrine 2 ? ake su tam rozdieli?

Ide o to ze mam jednu appku kde pouzivam Doctrine 2 a chcel by som ho nahradit niecim rychlejsim, ale pohodlnim :)

je LM to co hladam ?

Dokumentace

Můžu se zeptat, jak to vypadá s dokumentací? .(

Jak vyřešit ukládání serializovaných proměnných

Ukládám si v jedné entitě serializované pole.

/**
 * @property int $id
 * @property string $params m:passThru(unserialize|serialize)
 */
class Content extends BaseEntity {

    public function serialize($var)
    {
        return serialize($var);
    }

    public function unserialize($var)
    {
        return unserialize($var);
    }
}

Jenže pokud volám $params = $content->params;, tak mi LeanMapper zahlásí Notice: Array to string conversion, v File: .../vendor/tharos/leanmapper/LeanMapper/Entity.php:171

Dělám něco špatně nebo to takhle opravdu fungovat nemůže?

Add support for isset to Row columns

When working within entity with its row, I cannot determine if some column exists by isset php keyword. There is a method hasColumn() for that, but isset should be implemented the same way. Without it, it can cause unexpected behaviour.

// within Entity
$this->row->hasColumn("existing_column"); // works, returns TRUE
isset($this->row->existing_column); // returns FALSE

EDIT: empty should be implemented as well

Metoda Property::getAnnotation zpřístupňující originální anotaci

Rád bych navázal na tento komentář.

Jsem určitě pro komentář zpřístupnit. Otázkou pouze zůstává, jak nejlépe na to, protože parser nyní funguje tak, že si příznaky „vyzobává“ z celého řádku. On aktuálně neřeší místo, kde je poslední anotace.

Příklad namísto slov:

@property Book $book m:hasOne tohle je kniha m:filter(order)

Z tohoto zápisu parser vytáhne příznaky hasOne a filter. Co by vracela zamýšlená metoda Property::getDescription?

Docela se mi líbí, že to takhle funguje. Zvláště to oceníme, až brzy budou moci být anotace přes více řádků:

/**
 * @property Book[] $books
 *     m:hasOne    Knihy, které autor napsal
 *     m:filter(order#published)    Seřazené od nejstarších
 *
 * @property int $age    Věk autora
 *     m:form(unsigned, range: 1-99)    Metadata pro továrnu na formulář
 *
 * @property string|null $website
 */

Řešením by bylo zpřístupnit celou originální anotaci, řekněme pomocí metody Property::getAnnotation. To by bylo velmi jednoduché. Bylo by to dostatečné řešení?

Expected entityClass in the exception message

Hello,

File Repository.php (https://github.com/Tharos/LeanMapper/blob/develop/LeanMapper/Repository.php#L340) contains a line where the expected entity class name is not provided. I would suggest to change it in the following manner:

throw new InvalidArgumentException('Repository ' . get_called_class() . ' cannot handle ' . get_class($entity) . ' entity. Class name ' . $entityClass . ' was expected.');

It saves some time when debugging code.

Have a nice day!

Persisting an entity with Entity data type

I have a snipper of code:

    $user = new User();
    $user->email = $values->email;
    $user->password = $this->authenticator->calculateHash($values->password);
    $this->userRepository->persist($user);

Until here, everything is just fine, but

    $document = new Document;
    $document->user = $user;
    $document->type = $type;
    $document->path = $path;
    $this->documentRepository->persist($document);

throws dibi error, because it generates wrong insert sql (** unexpected object ** instead of entity's id).

I recommend you to add something similar to this:

protected function beforePersist(array $values)
{
    foreach (array_keys($values) as $key) {
        if ($values[$key] instanceof BaseEntity) {
            $values[$key] = $values[$key]->id;
        }
    }

    return $values;
}

Note: BaseEntity is defined as follows:

use LeanMapper\Entity;
/**
 * @property int $id
 */
class BaseEntity extends Entity
{

}

Entity: Persisting empty entity fails silently

Check out following code:

/**
 * @property int $userId
 * @property null|string $name
 */
class User extends BaseEntity {}

////////

$user = new User();
$userRepo->persist($user); // no exception here
$user->isDetached(); // returns true!
$user->userId; // Exception: Missing 'userId' value for requested row.


$user = new User();
$user->name= "John Doe";
$userRepo->persist($user);
$user->userId; // returns correct id

I know it is not so common, but I'm using these "just to exist" entities in some tests, where it is useful.

Mapper::getRelationshipColumn() posielat dalsi parameter $field

bolo by super kedy si do Mapper::getRelationshipColumn() posielal ako 3. paremeter $field

lebo mam:

@property \Tralandia\Language\Language $defaultLanguage m:hasOne

a nazov stlpca v DB mam defaultLanguage_id cize {$field}_id a preto by sa mi tam hodila ta premenna field

viem ze to mozem dopisat do m:hasOne(defaultLanguage_id:) ale ja to pouzivam ako konvenciu tak aby som to nemusel vsade dopisovat a vedel nastavit len na jednom mieste

co ty na to?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.