PHP code example of limingxinleo / swoft-db-model

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

    

limingxinleo / swoft-db-model example snippets

 
namespace SwoftTest\Db\Testing\Listener;

use Swoft\App;
use Swoft\Bean\Annotation\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use SwoftTest\Db\Testing\Entity\User;
use Xin\Swoft\Db\Driver\Mysql\MysqlConnection;
use Xin\Swoft\Db\Event\MysqlConnectionEvent;

/**
 * Model before save handler
 *
 * @Listener(MysqlConnectionEvent::AFTER_EXECUTE)
 */
class AfterExecuteListener implements EventHandlerInterface
{
    /**
     * @param \Swoft\Event\EventInterface $event
     */
    public function handle(EventInterface $event)
    {
        /** @var MysqlConnection $model */
        $model = $event->getConnection();

        $runtime = App::getAlias('@runtime');
        $file    = $runtime . '/sql.log';

        file_put_contents($file, $model->getSql() . PHP_EOL, FILE_APPEND);
    }

namespace App\Pool;

use Swoft\Bean\Annotation\Pool;
use Swoft\Db\Pool\DbPool as SwoftDbPool;
use Xin\Swoft\Db\Pool\CreateConnectionTrait;

/**
 * OtherDbPool
 *
 * @Pool("default.master")
 */
class DbPool extends SwoftDbPool
{
    use CreateConnectionTrait;

namespace App\Pool;

use Swoft\Bean\Annotation\Pool;
use Swoft\Db\Pool\DbSlavePool as SwoftDbSlavePool;
use Xin\Swoft\Db\Pool\CreateConnectionTrait;

/**
 * OtherDbSlavePool
 *
 * @Pool("default.slave")
 */
class DbSlavePool extends SwoftDbSlavePool
{
    use CreateConnectionTrait;

namespace SwoftTest\Db\Testing\Listener;

use Swoft\Bean\Annotation\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use SwoftTest\Db\Testing\Entity\User;
use Xin\Swoft\Db\Event\ModelEvent;

/**
 * Model before save handler
 *
 * @Listener(ModelEvent::BEFORE_SAVE)
 */
class BeforeSaveListener implements EventHandlerInterface
{
    /**
     * @param \Swoft\Event\EventInterface $event
     */
    public function handle(EventInterface $event)
    {
        /** @var User $model */
        $model = $event->getModel();
        if (method_exists($model, 'setCreatedAt') && method_exists($model, 'setUpdatedAt')) {
            $date = date('Y-m-d H:i:s');
            $model->setCreatedAt($date);
            $model->setUpdatedAt($date);
        }
    }