PHP code example of tomvlk / sweet-orm

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

    

tomvlk / sweet-orm example snippets


\SweetORM\ConnectionManager::injectConnection($pdo); // Where $pdo is an instance of PDO. Active connection!

\SweetORM\Configuration::set('database_driver',   'pdo_mysql');     // No other drivers support right now
\SweetORM\Configuration::set('database_host',     'localhost');
\SweetORM\Configuration::set('database_port',     3306);            // Optional, default 3306
\SweetORM\Configuration::set('database_db',       'sweet_test');
\SweetORM\Configuration::set('database_user',     'root');
\SweetORM\Configuration::set('database_password', '');

/**
 * @EntityClass
 * @Table(name="post")     <== The table has an attribute called 'name', which contains the table name in your database.
 */
class Post extends \SweetORM\Entity // Make sure you extend the SweetORM\Entity!
{
    /**
     * @Column(type="integer", primary=true, autoIncrement=true)
     */
    public $id;
    /**
     * @Column(type="integer")
     */
    public $authorid;
    /**
     * @Column(type="integer")
     */
    public $categoryid;
    /**
     * @var Category
     * @OneToOne(targetEntity="SweetORM\Tests\Models\Category")
     * @Join(column="categoryid", targetColumn="id")
     */
    public $category; // This will be a relation, the category holds a Category entity instance, lazy fetched from your 'categoryid' column!
    /**
     * @Column(type="string")
     */
    public $title;
    /**
     * @Column(type="string")
     */
    public $content;
}

/**
 * @EntityClass
 * @Table(name="category")
 */
class Category extends \SweetORM\Entity
{
    /**
     * @Column(type="integer", primary=true, autoIncrement=true)
     */
    public $id;
    /**
     * @Column(type="string")
     */
    public $name;
    /**
     * @Column(type="string")
     */
    public $description;

    // One To Many relationship
    /**
     * @var Post[]
     * @OneToMany(targetEntity="SweetORM\Tests\Models\Post")
     * @Join(column="id", targetColumn="categoryid")
     */
    public $posts;  // Will be available, and fetched when you refer to it using lazy loading.
}

$category = Category::get(1);

echo get_class($category); // Output: Category
echo $category->id; // Output: 1

$categories = Category::find()->all();
// $categories is now an array with all the categories in your database, all returned as Entity instances.

$category = new Category();

$category->name = "Samples";
$category->description = "Sample posts";

$category->save(); // -> returns true or false, true on success, false on failure, will also throw exceptions.

$category = Category::get(1);
$category->name = "Samples - Old";
$category->save(); // -> returns true or false.

$category = Category::get(1);

// Delete
$category->delete();

$category = Category::find()->where('name', 'News')->one();

$query = Category::find();

$query->select();
$query->select('id name'); // Only fetch id and name column (not property!).

$query->from('table'); // Select from table (not needed when using entity!)

$query->where('column', '=', 'value'); // Middle is optional, default '='.
$query->where(array('column' => 'value', 'column2' => array('=' => 'vallue2'))); // Complex where.

$query->limit(50); // Limit by 50 rows
$query->offset(10); // Offset by 10.

$query->all(); // Execute query, fetchAll.
$query->one(); // Execute query, fetch first row.


// Write,update,delete
$query->insert('table'); // Insert into table.
$query->into('table'); // optional!
$query->values(array('column' => 'value')); // Set insert data.
$query->apply(); // boolean

$query->update('table');
$query->set(array('column' => 'value')); // Set new data.
$query->where('id', 1);
$query->apply();

$query->delete('table');
$query->where('id', 1);
$query->apply();

class Test extends Entity {
    /**
     * @var string
     * @Column(type="string", null=true)
     * @Constraint(
     *     startsWith="www.",           <== Constraint for starting string.
     *     minLength=20                 <== Minimum string length.
     * )
     */
    public $longUrl;
}

    // We are going to use the ArrayValidator (will be selected automatically)
    $data = array(
        'longUrl' => 'www.verylongurlthatvalidatescorrectly.com'
    );
    $result = Test::validator($data)->test();

    $result->isSuccess(); // true
    $result->getErrors(); // empty array.

    // We are going to use the ArrayValidator (will be selected automatically)
    $data = array(
        'longUrl' => 'www.verylongurlthatvalidatescorrectly.com'
    );
    $entity = Test::validator($data)->create(); // Entity = instance of Test.

    $entity->save(); // true

    // We are going to use the ArrayValidator (will be selected automatically)
    $entity = Test::get(1); // Instance of already existing test entity.

    $data = array(
        'longUrl' => 'www.verylongurlthatvalidatescorrectly2.com'
    );
    Test::validator($data)->fill($entity); // Entity = instance of Test.

    $entity->save(); // true, is now updated!