I am having a model and would need to update the record. every time $count ($count = $post->save()) is being NULL. how is it possible to know whether this record saved or not. if saved, i want to display the following message 'Post updated' and if not the other message 'Post cannot update'.
This is always going to the else port. how can i know model updated correctly or not?
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$count = $post->save();
//var_dump($count); exit;
if ($count > 0) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
$this->_helper->flashMessenger->addMessage('Post cannot update');
}
Application_Model_Post code is as below,
class Application_Model_Post
{
/**
* #var int
*/
protected $_id;
/**
* #var string
*/
protected $_title;
/**
* #var string
*/
protected $_body;
/**
* #var string
*/
protected $_created;
/**
* #var string
*/
protected $_updated;
/**
* #var Application_Model_PostMapper
*/
protected $_mapper;
/**
* Class Constructor.
*
* #param array $options
* #return void
*/
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key=> $value) {
$method = 'set'.ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setId($id)
{
$this->_id = $id;
return $this;
}
public function getId()
{
return $this->_id;
}
public function setTitle($title)
{
$this->_title = (string) $title;
return $this;
}
public function getTitle()
{
return $this->_title;
}
public function setBody($body)
{
$this->_body = $body;
return $this;
}
public function getBody()
{
return $this->_body;
}
public function setCreated($ts)
{
$this->_created = $ts;
return $this;
}
public function getCreated()
{
return $this->_created;
}
/**
* Set data mapper.
*
* #param mixed $mapper
* #return Application_Model_Post
*/
public function setMapper($mapper)
{
$this->_mapper = $mapper;
return $this;
}
/**
* Get data mapper.
*
* Lazy loads Application_Model_PostMapper instance if no mapper
* registered.
*
* #return Application_Model_PostMapper
*/
public function getMapper()
{
if (null === $this->_mapper) {
$this->setMapper(new Application_Model_PostMapper());
}
return $this->_mapper;
}
/**
* Save the current post.
*
* #return void
*/
public function save()
{
$this->getMapper()->save($this);
}
public function getPost($id)
{
return $this->getMapper()->getPost($id);
}
/**
* Update the current post.
*
* #return void
*/
public function update($data, $where)
{
$this->getMapper()->update($data, $where);
}
/**
* Find a post.
*
* Resets entry state if matching id found.
*
* #param int $id
* #return Application_Model_Post
*/
public function find($id)
{
$this->getMapper()->find($id, $this);
return $this;
}
/**
* Fetch all posts.
*
* #return array
*/
public function fetchAll()
{
return $this->getMapper()->fetchAll();
}
}
getMapper refers to the class Application_Model_PostMapper.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Post');
}
return $this->_dbTable;
}
}
Class of Application_Model_DbTable_Post
class Application_Model_DbTable_Post extends Zend_Db_Table_Abstract
{
protected $_name = 'posts';
}
Let me know if anything is incorrect. i am a newbie to zend and did thsi while referring the zend site. http://framework.zend.com/manual/1.12/en/learning.quickstart.create-model.html
you can extend your script like this. zend dbtable triggers the Zend_Db_Exception on any error during any insert or update.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
try {
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
} catch (Zend_Db_Exception $e) {
// error thrown by dbtable class
return $e->getMessage();
}
// no error
return true;
}
}
now you can check like this
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$isSaved = $post->save();
if ($isSaved === true) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
// error
// $isSaved holds the error message
$this->_helper->flashMessenger->addMessage('Post cannot update');
}
Related
My entity :
class User{
id : int
name : string
boss : User()
}
I want to create a function that return an array() of users that work under a giving user.
example :
public function MyEmployers( User $user , array $usersList )
{
$myEmployers = array();
...
return $myEmployers;
}
$results = $this->myEmployers ( $employer1 , $allEmployers)
dump ( $results );
$results = [ 4 , 5 , 6 ];
I found a solution if someone can improve it feel free :
public $tree = array();
public function MyEmployers(User $user)
{
$superior_key_id = array();
$all_users = $this->getallusers();
$id = $user->getId();
foreach ($all_users as $user) {
if ($user->getSuperior())
$superior_key_id[$user->getSuperior()->getId()][] = $user;
}
$this->getSubEmployee($this->getUser(), $superior_key_id);
return ($this->tree);
}
public function getSubEmployee($user, $superior_key_id)
{
if (isset($superior_key_id[$user->getId()])) {
foreach ($superior_key_id[$user->getId()] as $user) {
$this->tree[] = $user;
$this->getSubEmployee($user, $superior_key_id);
}
}
return $user;
}
this one will get all bosses if you're interested :
public function MyBosses(User $user)
{
$bosses = array();
while ($user->getSuperior()) {
array_push($bosses, $user->getSuperior());
$user = $user->getSuperior();
}
return $bosses;
}
You could set up a one-to-many relationship between boss and employee
So you're user class could look like:
class User{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="employee")
*/
private $boss;
/**
* #ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="boss")
*/
private $employees;
public function __construct()
{
$this->employees = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* #return Collection|employees[]
*/
public function getEmployees(): Collection
{
return $this->employees;
}
public function addEmployee(employee $employee): self
{
if (!$this->employees->contains($employee)) {
$this->employees[] = $employee;
}
return $this;
}
public function removeEmployee(employee $employee): self
{
if ($this->employees->contains($employee)) {
$this->employees->removeElement($employee);
}
return $this;
}
public function getBoss(): ?Usesr
{
return $this->boss;
}
public function setBoss(?User $boss): self
{
$this->boss = $boss;
return $this;
}
}
You would need to set up the database relationship with the symfony make:entity command.
To get all employeers under a user, you could do something like:
function getAllEmployeesUnder(User $user)
{
$allEmployees = [];
foreach ($user->getEmployees as $employee) {
$allEmployees[] = $employee;
$allEmployees = array_merge($allEmployees, $this->getAllEmployeesUnder($employee));
}
return $allEmployees;
}
I have a problem.. When I execute this code:
public function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
private static $users = $this->korisnici();
It gives me this error: syntax error, unexpected '$this' (T_VARIABLE)..
Can someone help me, how can I call this function?
Here's my whole class:
class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public $arr;
public function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
public $users = $this->korisnici();
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
I'm trying to change this default model from Yii Framework so I can login using database...
Looks like you have copied it from a class. The following will work like a regular function. Still not sure where you get $modelk = new Korisnici(); from
function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
print_r(korisnici());
EDIT: After looking at your whole class:
You need to use the __construct method.
public function __construct()
{
$this->users = $this->korisnici();
}
Is it possible with laravel to retrieve a model property when using $queryBuilder->get() method ?
My database have weird naming convention (old app), and I have written one get*Attribute() method for each field, so I can access it by doing $model->prettyName, instead of $model->weird_Convention_Name, but when I use the $queryBuilder->get(), I get the database field, not the model properties.
Is there a way of doing this ?
EDIT
Here a sample of code:
Model
<?php
namespace Model\Day;
use Illuminate\Database\Eloquent\Builder;
/**
* Class Incomplete
* #package Model
* #subpackage Day
* #property string $alarm
* #property string $status
* #property string $mark1
* #property int $dayRate
* #property bool $isHalfDay
* #property bool $noPause
* #property bool $isTracked
* #property bool $noTime
* #property string $dayType
* #property string $shortDay
* #property \DateTime $date
* #property \DateTime $startDay
* #property \DateTime $startBreak
* #property \DateTime $endBreak
* #property \DateTime $startBreak2
* #property \DateTime $endBreak2
* #property \DateTime $endDay
* #property string $statusDescription
* #property string $subtype
* #property string $subcode
* #property string $description
* #property int $locationId
* #property string $locationDes
*
* #method \Eloquent currentUser()
*/
class Incomplete extends \Eloquent
{
/**
* The database table used by the model.
* #var string
*/
protected $table = 'vlogger_pending';
/**
* The primary key for the model.
* #var string
*/
protected $primaryKey = null;
/**
* The sequence name used for incrementing
* #var string
*/
protected $sequence = null;
/**
* Indicates if the IDs are auto-incrementing.
* #var bool
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
* #var bool
*/
public $timestamps = false;
/***********************************************************************
* SCOPES
***********************************************************************/
/**
* Add a where statement for current logged in user
* #param Builder $query
* #return Builder
*/
public function scopeCurrentUser(Builder $query)
{
return $query->where('usr_id', '=', \Auth::user()->id);
}
/***********************************************************************
* ACCESSORS
***********************************************************************/
public function getAlarmAttribute()
{
return $this->attributes['alarm'];
}
public function getStatusAttribute()
{
return $this->attributes['status'];
}
public function getMark1Attribute()
{
return $this->attributes['mark1'];
}
public function getDayRateAttribute()
{
return (int)$this->attributes['day_rate'];
}
public function getIsHalfDayAttribute()
{
return !!$this->attributes['half_day'];
}
public function getNoPauseAttribute()
{
return !!$this->attributes['no_pause'];
}
public function getIsTrackedAttribute()
{
return !!$this->attributes['tracked'];
}
public function getNoTimeAttribute()
{
return !!$this->attributes['no_hours'];
}
public function getDayTypeAttribute()
{
return $this->attributes['day_type'];
}
public function getShortDayAttribute()
{
return $this->attributes['dd'];
}
public function getDateAttribute()
{
$date = $this->attributes['day'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getStartDayAttribute()
{
$date = $this->attributes['dstart'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getStartBreakAttribute()
{
$date = $this->attributes['pstart'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getEndBreakAttribute()
{
$date = $this->attributes['pend'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getStartBreak2Attribute()
{
$date = $this->attributes['s_pstart2'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getEndBreak2Attribute()
{
$date = $this->attributes['s_pend2'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getEndDayAttribute()
{
$date = $this->attributes['dend'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getStatusDescriptionAttribute()
{
return $this->attributes['status_des'];
}
public function getSubtypeAttribute()
{
return $this->attributes['sub_type'];
}
public function getSubcodeAttribute()
{
return $this->attributes['sub_code'];
}
public function getDescriptionAttribute()
{
return $this->attributes['des'];
}
public function getLocationIdAttribute()
{
return (int)$this->attributes['location'];
}
public function getLocationDesAttribute()
{
return $this->attributes['location_des'];
}
/***********************************************************************
* MUTATORS
***********************************************************************/
public function setAlarmAttribute($value)
{
$this->attributes['alarm'] = $value;
return $this;
}
public function setStatusAttribute($value)
{
$this->attributes['status'] = $value;
return $this;
}
public function setMark1Attribute($value)
{
$this->attributes['mark1'] = $value;
return $this;
}
public function setDayRateAttribute($value)
{
$this->attributes['day_rate'] = $value;
return $this;
}
public function setIsHalfDayAttribute($value)
{
$this->attributes['half_day'] = $value;
return $this;
}
public function setNoPauseAttribute($value)
{
$this->attributes['no_pause'] = $value;
return $this;
}
public function setIsTrackedAttribute($value)
{
$this->attributes['tracked'] = $value;
return $this;
}
public function setNoTimeAttribute($value)
{
$this->attributes['no_hours'] = $value;
return $this;
}
public function setDayTypeAttribute($value)
{
$this->attributes['day_type'] = $value;
return $this;
}
public function setShortDayAttribute($value)
{
$this->attributes['dd'] = $value;
return $this;
}
public function setDateAttribute($value)
{
$this->attributes['day'] = $value;
return $this;
}
public function setStartDayAttribute($value)
{
$this->attributes['dstart'] = $value;
return $this;
}
public function setStartBreakAttribute($value)
{
$this->attributes['pstart'] = $value;
return $this;
}
public function setEndBreakAttribute($value)
{
$this->attributes['pend'] = $value;
return $this;
}
public function setStartBreak2Attribute($value)
{
$this->attributes['s_pstart2'] = $value;
return $this;
}
public function setEndBreak2Attribute($value)
{
$this->attributes['s_pend2'] = $value;
return $this;
}
public function setEndDayAttribute($value)
{
$this->attributes['dend'] = $value;
return $this;
}
public function setStatusDescriptionAttribute($value)
{
$this->attributes['status_des'] = $value;
return $this;
}
public function setSubtypeAttribute($value)
{
$this->attributes['sub_type'] = $value;
return $this;
}
public function setSubcodeAttribute($value)
{
$this->attributes['sub_code'] = $value;
return $this;
}
public function setDescriptionAttribute($value)
{
$this->attributes['des'] = $value;
return $this;
}
public function setLocationIdAttribute($value)
{
$this->attributes['location'] = $value;
return $this;
}
public function setLocationDesAttribute($value)
{
$this->attributes['location_des'] = $value;
return $this;
}
}
Controller
/**
* Get pending report for current logged user
* #return \Illuminate\Http\JsonResponse
*/
public function pendingReport()
{
return Response::json(Day\Incomplete::currentUser()->get());
}
Set $snakeAttributes in your model to false to use prettyName.
And use $appends to add formatted attribute when convert data to json.
class MyModel extends Eloquent {
public static $snakeAttributes = false;
protected $hidden = array('oldAttribute1', 'oldAttribute2');
protected $appends = array('attribute1', 'attribute2');
public function getAttribute1Attribute()
{
return 'Attribute1 Value';
}
public function getAttribute2Attribute()
{
return 'Attribute2 Value';
}
}
You can use "magick" __get():
private $aliases = array('
'prettyName' => 'weird_Convention_Name',
//...
');
public function __get($key)
{
if (!empty($this->aliases[$key]))
return parent::__get($this->aliases[$key]);
else
return parent::__get($key);
}
and always when you use $model->prettyName it return $model->weird_Convention_Name
I have installed a Magento Product Parts Interactive Diagram Extension in Magento CE 1.8.1.0.
The issue is it only renders one single Part Diagram per product. I need it to render all Diagrams for each product.
The code is :
public function getPartDiagram()
{
if ($this->getId()) {
return Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->load($this->getId());
}
if (Mage::registry('product')) {
$collection = Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->getCollection()
->addFieldToFilter('sku', Mage::registry('product')->getSku());
return $collection->getFirstItem();
}
return null;
}
If I return $collection->getLastItem(); it works and the last item is rendered on the front-end as expected.
But I cannot seem to get all items rendered, getItems does not work.
The code file is as follows, not sure but it might help.
<?php
/**
* Catalog product parts list block
*
* #category PWS
* #package ProductPartsDiagram
* #author Anda Bardeanu <info#pandawebstudio.com>
*/
class PWS_ProductPartsDiagram_Block_List extends Mage_Catalog_Block_Product_Abstract
{
protected $_productsCount = null;
const DEFAULT_PRODUCTS_COUNT = 5;
protected $_columnCount = 4;
protected $_items;
protected $_itemCollection;
protected $_itemLimits = array();
/**
* Initialize block's cache
*/
protected function _construct()
{
parent::_construct();
$this->addColumnCountLayoutDepend('empty', 6)
->addColumnCountLayoutDepend('one_column', 5)
->addColumnCountLayoutDepend('two_columns_left', 4)
->addColumnCountLayoutDepend('two_columns_right', 4)
->addColumnCountLayoutDepend('three_columns', 3);
$this->addData(array(
'cache_lifetime' => 86400,
'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG),
));
if (!$this->getData('template')) {
$this->setTemplate('pws_productpartsdiagram/list.phtml');
}
}
/**
* Get Key pieces for caching block content
*
* #return array
*/
public function getCacheKeyInfo()
{
return array(
'CATALOG_PRODUCT_PARTS_'.$this->getPartDiagram()->getId(),
Mage::app()->getStore()->getId(),
Mage::getDesign()->getPackageName(),
Mage::getDesign()->getTheme('template'),
Mage::getSingleton('customer/session')->getCustomerGroupId(),
'template' => $this->getTemplate(),
$this->getProductsCount()
);
}
/**
* Prepare collection with new products and applied page limits.
*
* return Mage_Catalog_Block_Product_New
*/
protected function _beforeToHtml()
{
$partDiagramId = -1;
$partDiagram = $this->getPartDiagram();
if ($partDiagram) {
$partDiagramId = $partDiagram->getId();
}
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$resource = Mage::getSingleton('core/resource');
$productsTable = $resource->getTableName('pws_productpartsdiagram_products');
// no pagination
$collection = $this->_addProductAttributesAndPrices($collection)
->addStoreFilter();
//->setPageSize($this->getProductsCount())
//->setCurPage(1);
$collection->getSelect()
->joinInner(
array('_table_products' => $productsTable),
'_table_products.product_id = e.entity_id',
array()
)
->from("", array('partdidagram_product_id'))
->where('_table_products.partdiagram_id = '. (int) $partDiagramId);
$this->setProductCollection($collection);
$this->_itemCollection = $collection;
return parent::_beforeToHtml();
}
/**
* Set how much product should be displayed at once.
*
* #param $count
* #return Mage_Catalog_Block_Product_New
*/
public function setProductsCount($count)
{
$this->_productsCount = $count;
return $this;
}
public function getPartDiagram()
{
if ($this->getId()) {
return Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->load($this->getId());
}
if (Mage::registry('product')) {
$collection = Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->getCollection()
->addFieldToFilter('sku', Mage::registry('product')->getSku());
return $collection->getFirstItem();
}
return null;
}
/**
* Get how much products should be displayed at once.
*
* #return int
*/
public function getProductsCount()
{
if (null === $this->_productsCount) {
$this->_productsCount = self::DEFAULT_PRODUCTS_COUNT;
}
return $this->_productsCount;
}
public function getItemCollection()
{
return $this->_itemCollection;
}
public function getItems()
{
if (is_null($this->_items)) {
$this->_items = $this->getItemCollection()->getItems();
}
return $this->_items;
}
public function getRowCount()
{
return ceil(count($this->getItemCollection()->getItems())/$this->getColumnCount());
}
public function setColumnCount($columns)
{
if (intval($columns) > 0) {
$this->_columnCount = intval($columns);
}
return $this;
}
public function getColumnCount()
{
return $this->_columnCount;
}
public function resetItemsIterator()
{
$this->getItems();
reset($this->_items);
}
public function getIterableItem()
{
$item = current($this->_items);
next($this->_items);
return $item;
}
/**
* Set how many items we need to show in block
* Notice: this parametr will be also applied
*
* #param string $type
* #param int $limit
* #return Mage_Catalog_Block_Product_List_Upsell
*/
public function setItemLimit($type, $limit)
{
if (intval($limit) > 0) {
$this->_itemLimits[$type] = intval($limit);
}
return $this;
}
public function getItemLimit($type = '')
{
if ($type == '') {
return $this->_itemLimits;
}
if (isset($this->_itemLimits[$type])) {
return $this->_itemLimits[$type];
}
else {
return 0;
}
}
}
I think you just want access to the collection of diagrams. So it might be simplest to add this code to your product view.phtml file:
$collection = Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->getCollection()
->addFieldToFilter('sku', Mage::registry('product')->getSku());
foreach($collection as $productpartsdiagram){
//code to display each diagram
}
Alternatively extend the class which has public function getPartDiagram() in it and add your own function:
public function getPartDiagramsAll()
{
if (Mage::registry('product')) {
$collection = Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->getCollection()
->addFieldToFilter('sku', Mage::registry('product')->getSku());
return $collection;
}
return null;
}
Call this function, then loop over the returned collection.
Hi everybody Im using doctrine ODM and have trouble with hydrator. I can't make extract on document with embed collection nor reference Class. the extract result for these class give me object and i really need to have them in array for rest module which is consumed by backbone implementation.
Here a example class :
Analyse.php Document
<?php
namespace Application\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
/**
* Application\Document\Analyse
*
* #ODM\Document(collection="analyse")
*/
class Analyse extends BaseDocument
{
/**
* #ODM\Id
*/
protected $id;
/**
* #ODM\Field(type="string")
*/
protected $nom;
/**
* #ODM\Field(type="string")
* #ODM\Index
*/
protected $alias;
/**
* #ODM\EmbedMany(targetDocument="ElementsAnalyse")
*/
protected $elements = array();
public function __construct()
{
parent::__construct();
$this->elements = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
public function getNom()
{
return $this->nom;
}
public function setAlias($alias)
{
$this->alias = $alias;
return $this;
}
public function getAlias()
{
return $this->alias;
}
public function addElements(Collection $elements)
{
foreach ($elements as $element) {
$this->elements->add($element);
}
}
public function removeElements(Collection $elements)
{
foreach ($elements as $item) {
$this->elements->removeElement($item);
}
}
public function getElements()
{
return $this->elements;
}
}
ElementAnalyse.php Collection
<?php
namespace Application\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
/**
* Application\Document\Valeurnormales
*
* #ODM\EmbeddedDocument
*
*/
class ElementsAnalyse
{
/**
* #ODM\Field(type="string")
*/
protected $nom;
/**
* #ODM\Field(type="string")
*/
protected $unite;
/**
* #ODM\EmbedMany(targetDocument="ValeurNormales")
*/
protected $valeurnormales = array();
/**
* #ODM\Field(type="string")
*/
protected $type;
public function __construct()
{
$this->valeurnormales = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set nom
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*/
public function getNom()
{
return $this->nom;
}
/**
* Set unite
*/
public function setUnite($unite)
{
$this->unite = $unite;
return $this;
}
/**
* Get unite
*
* #return string
*/
public function getUnite()
{
return $this->unite;
}
/**
* add valeurnormales
*/
public function addValeurnormales(Collection $vn)
{
foreach ($vn as $item) {
$this->valeurnormales->add($item);
}
}
public function removeValeurnormales(Collection $vn)
{
foreach ($vn as $item) {
$this->valeurnormales->removeElement($item);
}
}
/**
* Get valeurnormales
*/
public function getValeurnormales()
{
return $this->valeurnormales;
}
/**
* Set type
*
* #param $type
* #return Analyse
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return Type
*/
public function getType()
{
return $this->type;
}
/**
* toArray function
*/
public function toArray()
{
return get_object_vars($this);
}
/**
* fromArray function
*
*/
public function fromArray(array $array)
{
$objects = $this->toArray();
foreach($array as $item => $value)
{
if(array_key_exists($item, $objects))
{
$this->$item = $value;
}
}
}
}
Here my getList Method
public function getList()
{
$hydrator = new DoctrineHydrator($entityManager, 'Application\Document\Analyse');
$service = $this->getAnalyseService();
$results = $service->findAll();
$data = $hydrator->extract($results);
return new JsonModel($data);
}
And obviously var_dump($data['elements']) return object Collection or proxy class
Can You help me. Anything will be appreciated it been 2 weeks i can't make it work.
Read about Hydrator Strategy out there but i don't knnow how to implement it.
Currently, the Doctrine ODM implementation does not provide recursion for embedded objects and references.
If you use var_dump() on your $hydrator->extract($results), you'll see that all your embeds/references are there in their original object format.
What you can do here is to use Zend\Stdlib\Hydrator\Strategy, and define your own logic for extraction/hydration. Doctrine extends Zend Framework 2's hydrators and strategies.