PHP code example of elegant-bro / stringify

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

    

elegant-bro / stringify example snippets




use ElegantBro\Stringify\Stringify;

interface Connection
{
    public function execute(Stringify $query, array $params): void;
}



use ElegantBro\Stringify\Just;

// Let's change user's (which id is 10) first name to Jonh
$connection->execute(
    new Just('UPDATE users SET first_name = ? WHERE id = ?'),
    ['John', 10]
);



use ElegantBro\Stringify\Stringify;
use ElegantBro\Stringify\Imploded;
use ElegantBro\Stringify\Joined;
use ElegantBro\Stringify\Just;
use ElegantBro\Stringify\Formatted;

final class UpdateQuery implements Stringify
{
    private $table;
    private $fields;
    
    public function __construct(string $table, array $fields) 
    {
        $this->table = $table;
        $this->fields = $fields;
    }
    
    public function asString(): string
    {
        return 
            (new Joined(
                new Formatted(new Just('UPDATE %s SET '), $this->table),
                new Imploded(
                    new Just(' '),
                    array_map(
                        static function (string $field) { return $field.' = ?'; },
                        $this->fields
                    )
                )
            ))->asString();
    }
}



$connection->execute(
    new UpdateQuery('users', ['first_name']),
    ['John']
);



use ElegantBro\Stringify\Stringify;
use ElegantBro\Stringify\Imploded;
use ElegantBro\Stringify\Joined;
use ElegantBro\Stringify\Just;

final class Where implements Stringify
{
    private $origin;
    
    private $fields;
    
    public function __construct(Stringify $query, array $fields)
    {
        $this->origin = $query;
        $this->fields = $fields;
    }
    
    public function asString(): string
    {
        return 
            (new Joined(
                $this->origin,
                new Just(' WHERE '),
                new Imploded(
                    new Just(' '),
                    array_map(
                        static function (string $field) { return $field.' = ?'; },
                        $this->fields
                    )
                ) 
            ))->asString();
    }
}



$connection->execute(
    new Where(
        new UpdateQuery('users', ['first_name']),
        ['id']
    ),
    ['John', 10]
);