PHP code example of alphasoft-fr / data-model

1. Go to this page and download the library: Download alphasoft-fr/data-model 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/ */

    

alphasoft-fr / data-model example snippets


use AlphaSoft\DataModel\Model;

class UserModel extends Model
{
    protected static function getDefaultAttributes(): array
    {
        return [
            'fullName' => null,
            'age' => null,
            'isActive' => true,
        ];
    }

    protected static function getDefaultColumnMapping(): array
    {
        return [
            'fullName' => 'full_name',
            'age' => 'user_age',
        ];
    }
    
    public static function getPrimaryKeyColumn(): string
    {
        return 'id'; // Replace 'id' with the actual primary key column name
    }
}

$data = [
    'full_name' => 'John Doe',
    'user_age' => 30,
    // ...
];

$user = new UserModel($data);

// Alternatively
$user = new UserModel();
$user->hydrate($data);

$fullName = $user->getString('fullName');
$age = $user->getInt('age');

$user->set('age', 31);
$user->set('isActive', false);

$userArray = $user->toArray();

use YourNamespace\UserModel;
use PDO;

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=yourdb", "username", "password");

// Create a new UserModel instance
$user = new UserModel();
$user->set('fullName', 'Jane Smith');
$user->set('age', 25);

// Insert the new user data into the database
$columns = implode(', ', array_keys($user->toDb()));
$values = ':' . implode(', :', array_keys($user->toDb()));
$sql = "INSERT INTO users ($columns) VALUES ($values)";
$stmt = $pdo->prepare($sql);
foreach ($user->toDb() as $column => $value) {
    $stmt->bindValue(":$column", $value);
}
$stmt->execute();

$insertedPrimaryKeyValue = $pdo->lastInsertId();
echo "User inserted with primary key: $insertedPrimaryKeyValue\n";

use YourNamespace\UserModel;
use PDO;

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=yourdb", "username", "password");

// Retrieve user data from the database
$primaryKeyValue = 1; // Replace with the primary key value of the user you want to update
$sql = "SELECT * FROM users WHERE " . UserModel::getPrimaryKeyColumn() . " = :primaryKeyValue";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':primaryKeyValue', $primaryKeyValue);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);

// Create an instance of UserModel
$user = new UserModel($data);

// Modify object attributes
$user->set('fullName', 'Jane Smith');
$user->set('age', 25);

// Update the changes in the database
$updates = [];
foreach ($user->toDb() as $column => $value) {
    $updates[] = "$column = :$column";
}
$sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE " . UserModel::getPrimaryKeyColumn() . " = :" .UserModel::getPrimaryKeyColumn();
$stmt = $pdo->prepare($sql);
foreach ($user->toDb() as $column => $value) {
    $stmt->bindValue(":$column", $value);
}
$stmt->execute();

echo "User updated with primary key: $primaryKeyValue\n";

$lastname = $user->getString('lastname', 'Doe'); // Retrieves 'Doe' if 'lastname' exists and is a string

$age = $user->getInt('age', 25); // Retrieves 25 if 'age' exists and is an integer

$price = $product->getFloat('price', 0.0); // Retrieves 0.0 if 'price' exists and is a float

$isActive = $user->getBool('isActive', false); // Retrieves false if 'isActive' exists and is a boolean

$tags = $post->getArray('tags', []); // Retrieves an empty array if 'tags' exists and is an array

$profile = $user->getInstanceOf('profile', Profile::class); // Retrieves an instance of Profile or null if 'profile' exists and is an instance of Profile

$createdAt = $post->getDateTime('created_at', 'Y-m-d H:i:s'); // Retrieves a DateTimeInterface instance or null if 'created_at' exists and is convertible to a valid date

protected static function getDefaultAttributes(): array
{
    return [
        'id' => null,
        'fullName' => null,
        'age' => 0,
        'isActive' => true,
    ];
}

protected static function getDefaultColumnMapping(): array
{
    return [
        'fullName' => 'full_name',
        'age' => 'user_age',
        'isActive' => 'is_active',
    ];
}

public static function getPrimaryKeyColumn(): string
{
    return 'id'; // Replace 'id' with the actual primary key column name
}

use AlphaSoft\DataModel\Model;

class UserModel extends Model
{
    protected static function getDefaultAttributes(): array
    {
        return [
            'id' => null,
            'fullName' => null,
            'age' => null,
            'isActive' => true,
        ];
    }

    protected static function getDefaultColumnMapping(): array
    {
        return [
            'id' => 'user_id',
            'fullName' => 'full_name',
            'age' => 'user_age',
            'isActive' => 'is_active',
        ];
    }
    
    public static function getPrimaryKeyColumn(): string
    {
        return 'id'; // Replace 'id' with the actual primary key column name
    }
}

// ...

// Creating a UserModel instance
$userData = [
    'id' => 1,
    'fullName' => 'John Doe',
    'age' => 30,
    'isActive' => true,
];
$user = new UserModel($userData);

// Getting the primary key value
$primaryKeyValue = $user->getPrimaryKeyValue();
echo "Primary Key Value: $primaryKeyValue\n"; // Output: Primary Key Value: 1

use AlphaSoft\DataModel\Factory\ModelFactory;

$modelData = [
    'fullName' => 'John Doe',
    'age' => 30,
    // ... other properties
];

$model = ModelFactory::createModel(YourModelClass::class, $modelData);

$collectionData = [
    // ... array of model data
];

$collection = ModelFactory::createCollection(YourModelClass::class, $collectionData);

use AlphaSoft\DataModel\Factory\ModelFactory;
use YourNamespace\UserModel;

// Sample data for a single model instance
$modelData = [
    'fullName' => 'Jane Smith',
    'age' => 25,
    // ... other properties
];

// Create a single model instance
$model = ModelFactory::createModel(UserModel::class, $modelData);

// Sample data for a collection of model instances
$collectionData = [
    // ... array of model data
];

// Create a collection of model instances
$collection = ModelFactory::createCollection(UserModel::class, $collectionData);

// Use the $model and $collection objects as needed