Home >PHP Framework >Workerman >How does workerman call the database?

How does workerman call the database?

尚
Original
2019-12-23 16:43:183555browse

How does workerman call the database?

Dependent extensions

The mysql class depends on two extensions, pdo and pdo_mysql. If the extension is missing, Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' in . ...mistake.

Running php -m from the command line will list all php cli installed extensions

centos system

PHP5.x

yum install php-pdo
yum install php-mysql

PHP7.x

yum install php70w-pdo_dblib.x86_64
yum install php70w-mysqlnd.x86_64

Install Workerman/MySQL

Method 1:

can be installed through composer, run the following command on the command line (the composer source is abroad, the installation process may be very slow).

composer require workerman/mysql

After the above command is successful, the vendor directory will be generated, and then autoload.php under the vendor will be introduced into the project.

require_once __DIR__ . '/vendor/autoload.php';

workerman calls the database instance:

use Workerman\Worker;
require_once __DIR__ . '/Workerman/Autoloader.php';
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://0.0.0.0:8484');
$worker->onWorkerStart = function($worker)
{
    // 将db实例存储在全局变量中(也可以存储在某类的静态成员中)
    global $db;
    $db = new \Workerman\MySQL\Connection('host', 'port', 'user', 'password', 'db_name');
};
$worker->onMessage = function($connection, $data)
{
    // 通过全局变量获得db实例
    global $db;
    // 执行SQL
    $all_tables = $db->query('show tables');
    $connection->send(json_encode($all_tables));
};
// 运行worker
Worker::runAll();

For more workerman knowledge, please pay attention to the workerman tutorial column.

The above is the detailed content of How does workerman call the database?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn