PHP code example of compositephp / db

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

    

compositephp / db example snippets


#[Table(db: 'dbName', name: 'Users')]
class User extends AbstractEntity
{
    #[PrimaryKey(autoIncrement: true)]
    public readonly int $id;

    public function __construct(
        public string $email,
        public ?string $name = null,
        public bool $is_test = false,
        public array $languages = [],
        public Status $status = Status::ACTIVE,
        public readonly \DateTimeImmutable $created_at = new \DateTimeImmutable(),
    ) {}
}

enum Status
{
    case ACTIVE;
    case BLOCKED;
}

$table = new UsersTable();

//Create
$user = new User(
    email: '[email protected]',
    name: 'John',
    languages: ['en', 'fr'],
);
$table->save($user);

//Read
$user = $table->findByPk(123);

//Update
$user->status = Status::BLOCKED;
$table->save($user);

//Delete
$table->delete($user);

//Other selects out of the box
$table->findAll();
$table->countAll();

var_export($user->toArray());

//will output
array (
  'id' => 123,
  'email' => '[email protected]',
  'name' => 'John',
  'is_test' => false,
  'languages' => '["en","fr"]',
  'status' => 'BLOCKED',
  'created_at' => '2022-01-01 11:22:33.000000',
)

$user = User::fromArray([
  'id' => 123,
  'email' => '[email protected]',
  'name' => 'John',
  'is_test' => false,
  'languages' => '["en","fr"]',
  'status' => 'BLOCKED',
  'created_at' => '2022-01-01 11:22:33.000000',
]);
shell
$ php console.php composite-db:generate-entity dbName Users 'App\User'
shell
$ php console.php composite-db:generate-table 'App\User' 'App\UsersTable'