如何在slim 3

时间:2018-01-21 21:49:50

标签: php rest api slim slim-3

我只是学习苗条3并且我想将我的苗条2项目转换为苗条3但是仍然坚持PHP功能,尤其是参数。我不知道如何用参数创建函数以及如何传递它。

例如,我有一个重要的功能来获取我的用户详细信息,我不知道如何转换为Slim 3。

谢谢

function internalUserDetails($input) {
    
    try {
        $db = getDB(); //when convert to slim 3, I declared the DB in dependencies so I have to call the DB with '$this->db'
        $sql = "SELECT user_id, name, email, username FROM users WHERE username=:input or email=:input";
        $stmt = $db->prepare($sql);
        $stmt->bindParam("input", $input,PDO::PARAM_STR);
        $stmt->execute();
        $usernameDetails = $stmt->fetch(PDO::FETCH_OBJ);
        $usernameDetails->token = apiToken($usernameDetails->user_id);
        $db = null;
        return $usernameDetails;
        
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
    
}

这是数据库依赖代码

$container['db'] = function ($c) {
    $db = $c['settings']['db'];
    $pdo = new PDO('mysql:host=' . $db['host'] . ';dbname=' . $db['dbname'],
        $db['user'], $db['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};

当我跑步时出现错误

  

不在对象上下文中时使用$ this

2 个答案:

答案 0 :(得分:1)

在Slim 3中,您应该使用容器来获取数据库实例。

在文件config / settings.php中插入并调整必要的连接设置

// Database settings
$config['db']['host'] = '127.0.0.1';
$config['db']['username'] = 'root';
$config['db']['password'] = '';
$config['db']['database'] = 'test';
$config['db']['charset'] = 'utf8';
$config['db']['collation'] = 'utf8_unicode_ci';

为PDO连接添加容器条目

$container['db'] = function (Container $container) {
    $settings = $container->get('settings');
    $host = $settings['db']['host'];
    $dbname = $settings['db']['database'];
    $username = $settings['db']['username'];
    $password = $settings['db']['password'];
    $charset = $settings['db']['charset'];
    $collate = $settings['db']['collation'];
    $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_PERSISTENT => false,
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset COLLATE $collate"
    ];

    return new PDO($dsn, $username, $password, $options);
};

然后将PDO实例注入控制器类并通过成员变量访问它。

protected $db;

public function __construct(Container $container)
{
    $this->db = $container->get('db');
}

public function internalUserDetails(Request $request, Response $response)
{
    $this->db ...
}

如果使用路由回调,则访问PDO实例,如下所示:

$app->get('/', function (Request $request, Response $response, array $args) {
    $db = $this->get('db');
    // do something

    return $response;
});

答案 1 :(得分:0)

为您的数据库创建一个类:

<?php

class Database
{
    /**
     * Database username
     *
     * @var string
     */
    protected $username;

    /**
     * Database password
     *
     * @var string
     */
    protected $password;

    /**
     * Database host
     *
     * @var string
     */
    protected $host;

    /**
     * Database name
     *
     * @var string
     */
    protected $name;

    /**
     * Database constructor;
     */
    public function __construct()
    {
        try {

            // iniate $c... I'm not sure how you're getting the value..
            $c = [
                'settings' => [
                    'db' => [
                        'host'   => '',
                        'dbname' => '',
                        'user'   => '',
                        'pass'   => '',
                    ],
                ],
            ];
            $this->host     = $c['settings']['db']['host'];
            $this->name     = $c['settings']['db']['dbname'];
            $this->username = $c['settings']['db']['user'];
            $this->password = $c['settings']['db']['pass'];

            return $this->connect();
        }
    }

    /**
     * Connect to your database
     *
     * @return pdo
     */
    public function connect()
    {
        try{
            $pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->name,
            $this->username, $this->password);

            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

            return $pdo;   
        } catch (Exception $ex){
            return $ex->getMessage();
        }

    }

}

在课堂内创建一个_construct,例如:

/**
 * My Database
 *
 * @class 
 */
protected $db;

/**
 * Class constructor
 */
public function __construct(Database $database){
    $this->db = $database;
}

然后将分配您的$this->db,以便您可以在方法

中使用它