PHP code example of rds / hydrogen

1. Go to this page and download the library: Download rds/hydrogen 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/ */

    

rds / hydrogen example snippets




use Doctrine\ORM\EntityRepository;
use RDS\Hydrogen\Hydrogen;

class ExampleRepository extends EntityRepository 
{
    use Hydrogen;
}



use RDS\Hydrogen\Hydrogen;
use Doctrine\ORM\EntityRepository;

class UsersRepository extends EntityRepository 
{
    use Hydrogen;
    
    public function toArray(): iterable
    {
        return $this->query->get();
    }
}

foreach ($users->toArray() as $user) {
    \var_dump($user);
}



use RDS\Hydrogen\Hydrogen;
use Doctrine\ORM\EntityRepository;
use RDS\Hydrogen\Collection\Collection;

class UsersRepository extends EntityRepository 
{
    use Hydrogen;
    
    public function toCollection(): Collection
    {
        return $this->query->collect();
    }
}

$users->toCollection()->each(function (User $user): void {
    \var_dump($user);
});

$user = $repository->query->where('name', 'John')->first();

echo $user->getName();

[$name, $email] = $repository->query->where('name', 'John')->first('name', 'email');

echo $name . ' with email ' . $email;

$users = $repository->query->get('id', 'name');

foreach ($users as ['id' => $id, 'name' => $name]) {
    echo $id . ': ' . $name;
}

$count = $users->query->count(); 

$price = $prices->query->max('price');

$price = $prices->query
    ->where('user', $user)
    ->where('finalized', 1)
    ->avg('price');

$price = $prices->query
    ->select('AVG(price) as price')
    ->scalar('price', 'int');

['count' => $count] = $users->query
    ->select(['COUNT(id)' => 'count'])
    ->get();

echo $count;

$result = $users->query
    ->select(['COUNT(id)' => 'count'])
    ->scalar('count');

echo $result;

['messages' => $messages, 'user' => $user] = $users->query
    ->select(['COUNT(messages)' => 'messages'])
    ->withEntity('user')
    ->where('id', 23)
    ->first();

$messages = $query
    ->select([$query->column('user_id') => 'user_id'])
    ->withEntity('message')
    ->get('message', 'user_id');
    
foreach ($messages as ['message' => $message, 'user_id' => $id]) {
    echo $message->title . ' of user #' . $id; 
}

$users = $repository->query->where('votes', '=', 100)->get();

$users = $repository->query->where('votes', 100)->get();

$users = $repository->query
    ->where('votes', '>=', 100)
    ->get();
    
$users = $repository->query
    ->where('votes', '<>', 100)
    ->get();
    
$users = $repository->query
    ->where('votes', '<=', 100)
    ->get();

$users = $repository->query
    ->where('votes', '>', 100)
    ->orWhere('name', 'John')
    ->get();

$users = $repository->query
    ->where('votes', '>', 100)
    ->or->where('name', 'John')
    ->get();

$users = $repository->query
    ->whereBetween('votes', 1, 100)
    ->get();

$users = $repository->query
    ->where('name', 'John')
    ->orWhereBetween('votes', 1, 100)
    ->get();

$users = $repository->query
    ->whereNotBetween('votes', 1, 100)
    ->get();

$users = $repository->query
    ->where('name', 'John')
    ->orWhereNotBetween('votes', 1, 100)
    ->get();

$users = $repository->query
    ->whereIn('id', [1, 2, 3])
    ->get();

$users = $repository->query
    ->where('id', [1, 2, 3])
    // Equally: ->whereIn('id', [1, 2, 3])
    ->orWhere('id', [101, 102, 103])
    // Equally: ->orWhereIn('id', [101, 102, 103])
    ->get();

$users = $repository->query
    ->whereNotIn('id', [1, 2, 3])
    ->get();

$users = $repository->query
    ->where('id', '<>', [1, 2, 3])
    // Equally: ->whereNotIn('id', [1, 2, 3])
    ->orWhere('id', '<>', [101, 102, 103])
    // Equally: ->orWhereNotIn('id', [101, 102, 103])
    ->get();

$users = $repository->query
    ->whereNull('updatedAt')
    ->get();

$users = $repository->query
    ->where('updatedAt', null)
    // Equally: ->whereNull('updatedAt')
    ->orWhereNull('deletedAt', null)
    // Equally: ->orWhereNull('deletedAt')
    ->get();

$users = $repository->query
    ->whereNotNull('updatedAt')
    ->get();

$users = $repository->query
    ->whereNotNull('updatedAt')
    ->or->whereNotNull('deletedAt')
    ->get();

$messages = $repository->query
    ->like('description', '%some%')
    ->orLike('description', '%any%')
    ->get();

$messages = $repository->query
    ->where('description', '~', '%some%')
    ->orWhere('description', '~', '%any%')
    ->get();

$messages = $repository->query
    ->notLike('description', '%some%')
    ->orNotLike('description', '%any%')
    ->get();

$messages = $repository->query
    ->where('description', '!~', '%some%')
    ->orWhere('description', '!~', '%any%')
    ->get();

$users = $repository->query
    ->where('name', 'John')
    ->where(function (Query $query): void {
        $query->where('votes', '>', 100)
              ->orWhere('title', 'Admin');
    })
    ->get();

$users = $repository->query
    ->where('name', 'John')
    ->and(function (Query $query): void {
        $query->where('votes', '>', 100)
              ->orWhere('title', 'Admin');
    })
    ->get();
    
// SELECT u FROM App\Entity\User u 
// WHERE u.name = "John" AND (
//     u.votes > 100 OR
//     u.title = "Admin"
// )
    
$users = $repository->query
    ->where('name', 'John')
    ->or(function (Query $query): void {
        $query->where('votes', '>', 100)
              ->where('title', 'Admin');
    })
    ->get();
    
// SELECT u FROM App\Entity\User u 
// WHERE u.name = "John" OR (
//     u.votes > 100 AND
//     u.title = "Admin"
// )

$users = $repository->query
    ->orderBy('name', 'desc')
    ->get();

$users = $repository->query
    ->asc('id', 'createdAt')
    ->desc('name')
    ->get();

$users = $repository->query
     ->latest()
     ->get();
     
$posts = $repository->query
    ->oldest('updatedAt')
    ->get();

$users = $repository->query
     ->groupBy('account')
     ->get();

$users = $repository->query
     ->groupBy('firstName', 'status')
     ->get();

$users = $repository->query
    ->groupBy('account')
    ->having('account.id', '>', 100)
    ->get();

$users = $repository->query->skip(10)->take(5)->get();

$users = $repository->query
    ->offset(10)
    ->limit(5)
    ->get();

$articles = $repository->query
    ->where('category', 'news')
    ->after('id', 15)
    ->take(10)
    ->get();

$articles = $repository->range(10, 20)->get();



/**
 * @ORM\Entity(repositoryClass=UsersRepository::class)
 */
class User
{
    /**
     * @ORM\Embedded(class=Address::class) 
     */
    private $address;
}

/**
 * @ORM\Embeddable()
 */
class Address
{
    /**
     * @ORM\Column(type="string") 
     */
    private $city;

    /** 
     * @ORM\Column(type="string") 
     */
    private $country;
}



class UsersRepository extends EntityRepository
{
    use Hydrogen;
    
    public function findAllOrderedByCountry(): iterable
    {
        return $this->query->asc('address.country')->get();
    }
}



/** 
 * @ORM\Entity() 
 */
class Customer
{
    /** .... */
    
    /**
     * @ORM\OneToOne(targetEntity=Cart::class, mappedBy="customer")
     */
    private $cart;
}

/** 
 * @ORM\Entity() 
 */
class Cart
{
    /** .... */
    
    /**
     * @ORM\OneToOne(targetEntity=Customer::class, inversedBy="cart")
     * @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
     */
    private $customer;
}

$customers = $customerRepository->query
    ->join('cart')
    ->get();

foreach ($customers as $customer) {
    echo $customer->cart->id;
}

$customers = $customerRepository->query
     ->join(['cart' => function (Query $query): void {
         $query->where('balance', '>', 100)
            ->where('currency', 'RUB');
     }])
     ->get();

$customers = $customerRepository->query
     ->join(['cart.goods' => function (Query $query): void {
         $query->where('category', 'tickets')
            ->where('value', '>', 0);
     }])
     ->get();



class UsersRepository extends EntityRepository
{
    use Hydrogen;
    
    public function banned(bool $positive = true): Query
    {
        return $positive
            ? $this->query->whereNotNull('bannedAt')
            : $this->query->whereNull('bannedAt');
    }
    
    public function findBanned(): iterable
    {
        // We supplement the query, call the existing method "banned"
        return $this->query->banned->get();
    }
    
    public function findActive(): iterable
    {
        // We supplement the query, call the existing method "banned" with additional argument "false"
        return $this->query->banned(false)->get();
    }
} 

use RDS\Hydrogen\Collection;

$data = [
    ['value' => '23'],
    ['value' => '42'],
    ['value' => 'Hello!'],
];


$example1 = Collection::make($data)
    ->map->value // ['23', '42', 'Hello!']
    ->toArray();
    
//
// $example1 = \array_map(function (array $item): string {
//      return $item['value']; 
// }, $data);
//

$example2 = Collection::make($data)
    ->map->value     // ['23', '42', 'Hello!']
    ->map->intval(_) // [23, 42, 0]
    ->filter()       // [23, 42]
    ->toArray();
    
//
//
// $example2 = \array_map(function (array $item): string {
//      return $item['value']; 
// }, $data);
//
// $example2 = \array_map(function (string $value): int {
//      return \intval($value);
//                      ^^^^^ - pattern "_" will replaced to each delegated item value. 
// }, $example1);
//
// $example2 = \array_filter($example2, function(int $value): bool {
//      return (bool)$value;
// });
//
//

$example3 = Collection::make($data)
    ->map->value            // ['23', '42', 'Hello!']
    ->map->mbSubstr(_, 1)   // Using "mb_substr(_, 1)" -> ['3', '2', 'ello!']
    ->toArray();

use RDS\Hydrogen\Collection;

$collection = Collection::make([
    ['a' => 'A1', 'b' => 'B1' 'value' => '23'],
    ['a' => 'A2', 'b' => 'B2' 'value' => '42'],
    ['a' => 'A3', 'b' => 'B3' 'value' => 'Hello!'],
]);

// Displays all data
foreach($collection as $item) {
    \var_dump($item); // [a => 'A*', b => 'B*', value => '***'] 
}

// Displays only "a" field
foreach ($collection as ['a' => $a]) {
    \var_dump($a); // 'A'
}