PHP code example of indigerd / yii2-embedded-models
1. Go to this page and download the library: Download indigerd/yii2-embedded-models library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
indigerd / yii2-embedded-models example snippets
# configure default Hydrator object in your DI
Yii::$container->set(
'Indigerd\Hydrator\Accessor\AccessorInterface',
'Indigerd\Hydrator\Accessor\PropertyAccessor'
);
Yii::$container->set(
'Indigerd\Hydrator\Hydrator'
);
# Primary ("parent") model
use Indigerd\Hydrator\Hydrator;
use indigerd\embedded\behavior\HydrateBehavior;
use indigerd\embedded\behavior\HydrateCollectionBehavior;
use indigerd\embedded\model\mongodb\ActiveRecord;
class Clinic extends ActiveRecord
{
public static function collectionName(): string
{
return 'clinics';
}
public function attributes(): array
{
return [
'_id',
'name',
'country',
'doctors',
];
}
public function behaviors() : array
{
return [
[
'class' => HydrateBehavior::class,
'hydrator' => Hydrator::class,
'targetModel' => Country::class,
'attribute' => 'country'
],
[
'class' => HydrateCollectionBehavior::class,
'hydrator' => Hydrator::class,
'targetModel' => Doctor::class,
'attribute' => 'doctors'
],
];
}
}
# Country model
use yii\base\Model;
class Country extends Model
{
protected $name;
protected $code;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setCode($code)
{
$this->code = $code;
}
public function getCode()
{
return $this->code;
}
public function fields() : array
{
return [
'name',
'code'
];
}
}
# Doctor model
use indigerd\embedded\model\Model;
class Doctor extends Model
{
protected $name;
protected $contact;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setContact(Contact $contact)
{
$this->contact = $contact;
}
public function getContact()
{
return $this->contact;
}
public function fields() : array
{
return [
'name',
'contact'
];
}
public function behaviors() : array
{
return [
[
'class' => HydrateBehavior::class,
'hydrator' => Hydrator::class,
'targetModel' => Contact::class,
'attribute' => 'contact'
],
];
}
}
# Contact model
use yii\base\Model;
class Contact extends Model
{
protected $phone;
protected $email;
public function setPhone($phone)
{
$this->phone = $phone;
}
public function getPhone()
{
return $this->phone;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getEmail()
{
return $this->email;
}
public function fields() : array
{
return [
'phone',
'email'
];
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.