PHP code example of nilportugues / mongodb-repository
1. Go to this page and download the library: Download nilportugues/mongodb-repository 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/ */
nilportugues / mongodb-repository example snippets
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\Identity;
class User implements Identity
{
protected $userId;
protected $username;
protected $alias;
protected $email;
protected $registeredOn;
/**
* User constructor.
*
* @param $userId
* @param $username
* @param $alias
* @param $email
* @param \DateTime $registeredOn
*/
public function __construct($userId, $username, $alias, $email, \DateTime $registeredOn)
{
$this->userId = $userId;
$this->username = $username;
$this->alias = $alias;
$this->email = $email;
$this->registeredOn = $registeredOn;
}
// ... your getters/setters
public function id()
{
return $this->userId;
}
public function __toString()
{
return (string) $this->id();
}
}
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\Mapping;
class UserMapping implements Mapping
{
/**
* Name of the identity field in storage.
*/
public function identity() : string
{
return 'user_id';
}
/**
* Returns the table name.
*/
public function name() : string
{
return 'users';
}
/**
* Keys are object properties without property defined in identity().
* Values its MongoDB column equivalents.
*/
public function map() : array
{
return [
'userId' => 'user_id',
'username' => 'username',
'alias' => 'public_username',
'email' => 'email',
// Notice how we are accessing date value inside
// the \DateTime object! We use dot notation to
// access deep values.
'registeredOn.date' => 'created_at',
];
}
/**
* @param array $data
* @return User
*/
public function fromArray(array $data)
{
return new User(
$data['user_id'],
$data['username'],
$data['public_username'],
$data['email'],
new \DateTime($data['created_at'])
);
}
/**
* The automatic generated strategy used will be the data-store's if set to true.
*/
public function autoGenerateId() : bool
{
return true;
}
}
use MongoDB\Client;
use NilPortugues\Foundation\Infrastructure\Model\Repository\MongoDB\MongoDBRepository;
use NilPortugues\Foundation\Infrastructure\Model\Repository\MongoDB\MongoDBRepositoryHydrator;
class UserRepository extends MongoDBRepository
{
use MongoDBRepositoryHydrator;
}
$client = new Client();
$mapping = new UserMapping();
$repository = new UserRepository($mapping, $client, 'example_db', 'users');
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.