PHP code example of dedsecteam17 / soft-mapper

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

    

dedsecteam17 / soft-mapper example snippets









// 1. Configure database connection
apper.php';

class User extends SoftMapper
{
    public $table_name = "users";
    public $columns = [];

    public function __construct()
    {
        parent::__construct();
    }
}

// 3. Use the model
$user = new User();

// Insert a new user
$user->columns['name'] = 'John Doe';
$user->columns['email'] = '[email protected]';
$user->insert();

// Fetch all users
$all_users = $user->all()->getAll();


define('host', 'localhost');      // Database host
define('dbname', 'your_database'); // Database name
define('user', 'your_username');   // Database username
define('password', 'your_password'); // Database password


define('host', getenv('DB_HOST') ?: 'localhost');
define('dbname', getenv('DB_NAME') ?: 'softmapper');
define('user', getenv('DB_USER') ?: 'root');
define('password', getenv('DB_PASSWORD') ?: '');


s Post extends SoftMapper
{
    public $table_name = "posts";  // Your table name
    public $columns = [];          // Array to hold column values

    public function __construct()
    {
        parent::__construct();
    }
}

$post = new Post();
$post->columns['title'] = 'My First Post';
$post->columns['body'] = 'This is the content of my post.';
$post->columns['author_id'] = 1;
$post->columns['status'] = 'published';
$post->columns['created_at'] = date('Y-m-d H:i:s');

if ($post->insert()) {
    echo "Post created successfully!";
}

$post = new Post();
$result = $post->find(1);

if ($result) {
    echo $result->title;
}

$post = new Post();
$all_posts = $post->all()->getAll();

foreach ($all_posts as $p) {
    echo $p->title . "<br>";
}

$post = new Post();
$single_post = $post->all()->where([['id', '=', 1]])->get();

$post = new Post();
$results = $post->select(['title', 'author_id', 'created_at'])->getAll();

$post = new Post();
$post->columns['title'] = 'Updated Title';
$post->columns['body'] = 'Updated content';
$post->columns['updated_at'] = date('Y-m-d H:i:s');

$post->update()->where([['id', '=', 1]])->execute();

$post = new Post();
$post->columns['status'] = 'archived';

$post->update()
    ->where([
        ['created_at', '<', '2023-01-01', 'AND'],
        ['status', '=', 'draft']
    ])
    ->execute();

$post = new Post();
$post->delete()->where([['id', '=', 1]])->execute();

$post = new Post();
$post->delete()
    ->where([['status', '=', 'spam']])
    ->execute();

$post = new Post();
$results = $post->all()
    ->where([['status', '=', 'published']])
    ->getAll();

$post = new Post();
$results = $post->all()
    ->where([
        ['status', '=', 'published', 'AND'],
        ['author_id', '=', 5]
    ])
    ->getAll();

$post = new Post();
$results = $post->all()
    ->where([
        ['views', '>', 100, 'AND'],
        ['created_at', '>=', '2024-01-01']
    ])
    ->getAll();

$post = new Post();
$results = $post->all()
    ->orderBy('created_at', 'DESC')
    ->getAll();

$post = new Post();
$results = $post->all()
    ->orderBy('title', 'ASC')
    ->getAll();

$post = new Post();
$results = $post->all()
    ->limit(10)
    ->getAll();

$post = new Post();
$page = 2;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// Note: For offset, you may need to enhance the library
$results = $post->all()
    ->orderBy('created_at', 'DESC')
    ->limit($per_page)
    ->getAll();

$post = new Post();
$results = $post->all()
    ->where([
        ['status', '=', 'published', 'AND'],
        ['author_id', '=', 5]
    ])
    ->orderBy('created_at', 'DESC')
    ->limit(5)
    ->getAll();

$post = new Post();
$result = $post->select([], 'COUNT', '*')->get();
echo "Total posts: " . $result->{'COUNT(*)'};

$post = new Post();
$results = $post->select(['author_id'], 'COUNT', 'id')
    ->groupBy('author_id')
    ->getAll();

foreach ($results as $result) {
    echo "Author {$result->author_id} has {$result->{'COUNT(id)'}} posts<br>";
}

// Sum of all views
$post = new Post();
$result = $post->select([], 'SUM', 'views')->get();

// Average views
$result = $post->select([], 'AVG', 'views')->get();

// Maximum views
$result = $post->select([], 'MAX', 'views')->get();

// Minimum views
$result = $post->select([], 'MIN', 'views')->get();

$post = new Post();
$results = $post->select(['author_id'], 'COUNT', 'id')
    ->groupBy('author_id')
    ->having([['COUNT(id)', '>', 5]])
    ->getAll();

class Post extends SoftMapper
{
    public $table_name = "posts";
    public $columns = [];
    
    // Enable automatic timestamps (default: true)
    protected $timestamps = true;

    public function __construct()
    {
        parent::__construct();
    }
}

$post = new Post();
$post->columns['title'] = 'My Post';
$post->insert();
// created_at and updated_at are automatically set

// Update also automatically updates updated_at
$post->columns['title'] = 'Updated Title';
$post->update()->where([['id', '=', 1]])->execute();
// updated_at is automatically updated

class Post extends SoftMapper
{
    public $table_name = "posts";
    public $columns = [];
    
    // Enable soft deletes
    protected $soft_deletes = true;

    public function __construct()
    {
        parent::__construct();
    }
}

// Soft delete (sets deleted_at timestamp)
$post = new Post();
$post->delete()->where([['id', '=', 1]])->execute();

// Get only soft-deleted records
$trashed = $post->onlyTrashed()->getAll();

// Include soft-deleted in results
$all = $post->withTrashed()->all()->getAll();

// Restore a soft-deleted record
$post->restore()->where([['id', '=', 1]])->execute();

// Force delete (permanent)
$post->delete(true)->where([['id', '=', 1]])->execute();

class Post extends SoftMapper
{
    public $table_name = "posts";
    public $columns = [];
    
    // Custom primary key
    protected $primary_key = 'post_id';

    public function __construct()
    {
        parent::__construct();
    }
}

$post = new Post();
$result = $post->find(123); // Uses 'post_id' instead of 'id'

$post = new Post();
$page = 2;
$per_page = 10;
$offset = ($page - 1) * $per_page;

$results = $post->all()
    ->orderBy('created_at', 'DESC')
    ->limit($per_page)
    ->offset($offset)
    ->getAll();

$post = new Post();
$records = [
    ['title' => 'Post 1', 'body' => 'Content 1', 'author_id' => 1],
    ['title' => 'Post 2', 'body' => 'Content 2', 'author_id' => 2],
    ['title' => 'Post 3', 'body' => 'Content 3', 'author_id' => 1],
];

$result = $post->insertMany($records);

$post = new Post();
$results = $post->all()
    ->whereIn('id', [1, 2, 3, 5, 8])
    ->getAll();

$post = new Post();
$results = $post->all()
    ->whereNotIn('status', ['draft', 'archived'])
    ->getAll();

$post = new Post();
$results = $post->all()
    ->whereBetween('views', 100, 1000)
    ->getAll();

$post = new Post();
$with_featured = $post->all()
    ->whereNotNull('featured_image')
    ->getAll();

$without_category = $post->all()
    ->whereNull('category_id')
    ->getAll();

class Post extends SoftMapper
{
    public $table_name = "posts";
    public $columns = [];

    public function __construct()
    {
        parent::__construct();
        
        // Define a 'published' scope
        $this->scope('published', function($query) {
            $query->where([['status', '=', 'published']]);
        });
        
        // Define a 'popular' scope with parameters
        $this->scope('popular', function($query, $min_views = 1000) {
            $query->where([['views', '>', $min_views]]);
        });
    }
}

// Use scopes
$post = new Post();
$published = $post->all()->applyScope('published')->getAll();
$popular = $post->all()->applyScope('popular', 500)->getAll();

// INNER JOIN
$post = new Post();
$results = $post->select(['posts.title', 'users.name'])
    ->join('users', 'posts.author_id', '=', 'users.id')
    ->getAll();

// LEFT JOIN
$post = new Post();
$results = $post->select(['posts.*', 'categories.name'])
    ->leftJoin('categories', 'posts.category_id', '=', 'categories.id')
    ->getAll();

// RIGHT JOIN
$post = new Post();
$results = $post->select(['posts.*', 'tags.name'])
    ->rightJoin('tags', 'posts.tag_id', '=', 'tags.id')
    ->getAll();

$post = new Post();
$latest = $post->all()
    ->orderBy('created_at', 'DESC')
    ->first();

$post = new Post();
$total = $post->all()->count();
$published_count = $post->all()->where([['status', '=', 'published']])->count();

$post = new Post();
$has_posts = $post->all()->exists();
$has_published = $post->all()->where([['status', '=', 'published']])->exists();

$post = new Post();
$titles = $post->all()->pluck('title');
// Returns: ['Title 1', 'Title 2', 'Title 3']

$post = new Post();

try {
    $post->beginTransaction();
    
    $post->columns['title'] = 'Post 1';
    $post->insert();
    
    $post->columns['title'] = 'Post 2';
    $post->insert();
    
    $post->commit();
    echo "Transaction committed";
} catch (Exception $e) {
    $post->rollback();
    echo "Transaction rolled back";
}

$post = new Post();
$results = $post->raw(
    "SELECT status, COUNT(*) as count FROM posts WHERE created_at > :date GROUP BY status",
    ['date' => '2024-01-01']
);

$post = new Post();
$post->all()->chunk(100, function($posts) {
    // Process 100 posts at a time
    foreach ($posts as $p) {
        // Process each post
    }
});

$post = new Post();
$result = $post->updateOrCreate(
    ['slug' => 'my-unique-post'],
    ['title' => 'My Unique Post', 'body' => 'Content', 'status' => 'published']
);

$post = new Post();
$unique_authors = $post->select(['author_id'])->distinct()->getAll();

$post = new Post();
$post->columns['title'] = 'New Post';
$post->insert();
$last_id = $post->lastInsertId();
echo "New post ID: " . $last_id;

class User extends SoftMapper
{
    public $table_name = "users";
    
    // One-to-Many: User has many posts
    public function posts()
    {
        return $this->hasMany('Post', 'user_id', 'id');
    }
    
    // One-to-One: User has one profile
    public function profile()
    {
        return $this->hasOne('UserProfile', 'user_id', 'id');
    }
}

class Post extends SoftMapper
{
    public $table_name = "posts";
    
    // Belongs To: Post belongs to a user
    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id');
    }
    
    // One-to-Many: Post has many comments
    public function comments()
    {
        return $this->hasMany('Comment', 'post_id', 'id');
    }
    
    // Many-to-Many: Post belongs to many tags
    public function tags()
    {
        return $this->belongsToMany('Tag', 'post_tag', 'post_id', 'tag_id');
    }
}

$user = new User();
$user_record = $user->find(1);

// Load the posts relationship
$user->loadRelation('posts', $user_record);

// Access related data
foreach ($user_record->posts as $post) {
    echo $post->title . "\n";
}

$post = new Post();

// Load posts with users and comments in one query
$posts = $post->with(['user', 'comments'])->all()->getAll();

foreach ($posts as $p) {
    echo "Post: " . $p->title . "\n";
    echo "Author: " . $p->user->name . "\n";
    echo "Comments: " . count($p->comments) . "\n";
}

$post = new Post();

// Attach a tag to a post
$post->attach(1, 5, 'tags'); // Attach tag ID 5 to post ID 1

// Detach a tag from a post
$post->detach(1, 'tags', 5); // Detach tag ID 5 from post ID 1

// Sync tags (replace all existing with new ones)
$post->sync(1, [1, 2, 3], 'tags'); // Post ID 1 now has tags 1, 2, 3

// Create user and posts with relationships
$user = new User();
$user->columns = ['name' => 'John Doe', 'email' => '[email protected]'];
$user->insert();
$user_id = $user->lastInsertId();

$post = new Post();
$post->columns = [
    'user_id' => $user_id,
    'title' => 'My First Post',
    'body' => 'This is my first post!',
    'status' => 'published'
];
$post->insert();
$post_id = $post->lastInsertId();

// Attach tags to post
$post->attach($post_id, 1, 'tags'); // Tag: PHP
$post->attach($post_id, 2, 'tags'); // Tag: MySQL

// Load post with all relationships
$loaded_post = $post->with(['user', 'comments', 'tags'])->find($post_id);

echo "Post: " . $loaded_post->title . "\n";
echo "Author: " . $loaded_post->user->name . "\n";
echo "Tags: " . count($loaded_post->tags) . "\n";

[
    ['column_name', 'operator', 'value', 'logical_operator'],
    ['column_name', 'operator', 'value']  // Last condition doesn't need logical operator
]


t = new Post();

// Get all published posts ordered by date
$published_posts = $post->all()
    ->where([['status', '=', 'published']])
    ->orderBy('created_at', 'DESC')
    ->getAll();

// Get popular posts (views > 1000)
$popular_posts = $post->all()
    ->where([['views', '>', 1000]])
    ->orderBy('views', 'DESC')
    ->limit(5)
    ->getAll();

// Count posts by status
$post_counts = $post->select(['status'], 'COUNT', 'id')
    ->groupBy('status')
    ->getAll();


class User extends SoftMapper
{
    public $table_name = "users";
    public $columns = [];

    public function __construct()
    {
        parent::__construct();
    }
}

$user = new User();

// Register new user
$user->columns['username'] = 'johndoe';
$user->columns['email'] = '[email protected]';
$user->columns['password'] = password_hash('secret', PASSWORD_DEFAULT);
$user->columns['created_at'] = date('Y-m-d H:i:s');
$user->insert();

// Find user by email
$found_user = $user->all()
    ->where([['email', '=', '[email protected]']])
    ->get();

// Safe from SQL injection
$post = new Post();
$user_input = $_GET['id']; // Even malicious input is safe
$result = $post->find($user_input);

$post = new Post();

// Validate input
$title = filter_var($_POST['title'], FILTER_SANITIZE_STRING);
$body = filter_var($_POST['body'], FILTER_SANITIZE_STRING);

if (strlen($title) > 0 && strlen($body) > 0) {
    $post->columns['title'] = $title;
    $post->columns['body'] = $body;
    $post->insert();
} else {
    echo "Invalid input";
}

// In getAll(), get(), or execute() methods, add:
var_dump($this->built_query);
var_dump($this->query_columns_place_holder_array);
ini
extension=pdo
extension=pdo_mysql