Home >Backend Development >PHP Tutorial >PHP's Laravel framework combines the use and deployment of MySQL and Redis database, laravelredis_PHP tutorial

PHP's Laravel framework combines the use and deployment of MySQL and Redis database, laravelredis_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:56:14926browse

PHP's Laravel framework is combined with MySQL and Redis database usage and deployment, laravelredis

Rather than familiarizing yourself with official documents, it is more important to set up the framework environment.
Zero, environment introduction

  • Operating system: centOS
  • Database: mysql 5.6 (Alibaba Cloud RDS)
  • PHP 5.4.4 (>=5.4 is enough)
  • Laravel 5.0

1. Install LNMP
Before installing Laravel, you need to set up the Linux Nginx Mysql Php environment. The specific construction steps will not be detailed here.
P.S.

  • Linux Alibaba Cloud already comes with it. This article uses centOS 6.5 64-bit ECS
  • Regarding the choice between Nginx and Apache, it depends on your own preferences. This article uses the reverse proxy expert Nginx
  • Whether to install Mysql depends on your own situation. For example, if you use Alibaba Cloud's RDS, then there is no need to install it

2. Install Composer
Composer is a tool used to manage PHP package dependencies. Laravel is using this tool for dependency management. There are two installation methods

Partial installation
Global installation means it can be used in any directory of the system. This article only introduces this installation method. Official installation documentation

Execute the following two commands respectively

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

The installation is complete, use the following command to check whether the installation is successful

composer -V

The version number appears, which means the installation is successful

3. Install Laravel
Just follow Laravel’s official documentation. It is recommended to use [installation tool through Laravel]. There are no pitfalls. Skip it here
Tip: Since Laravel also depends on some PHP extensions, use yum to install

sudo install yum php-mysql php-mcrypt php-mbstring php-tokenizer php-openssl

After the installation is complete, add the following configuration at the bottom of the Nginx configuration file (usually /etc/nginx/conf.d/default.conf)

location / {
  try_files $uri $uri/ /index.php?$query_string;
}

Go to your laravel project directory and see the storage and vendor folders. Use the following commands to modify its file read and write permissions so that Nginx users can read and write it

sudo chmod -R 766 storage
sudo chmod -R 766 vendor

4. Let MVC run!
Before this, you should read the official documentation on routing, controllers, database usage basics, Eloquent ORM
At this point, you can start coding and develop an MVC demo. The function of this demo is to read the database table tbl_item from the database and respond to the browser in json format.
Assume that you have initialized your web app through laravel new demo.

  • Create a database (demo) and a table (tbl_item) in the database (fields can be determined as desired)
  • Configuration configuration file config/database.php
  • Directly operate the database and insert a piece of data into tbl_item
  • Start coding

Add the following code at the bottom of demo/app/http/routes.php:

Route::get('/item/{id}', 'ItemController@showItem');

Add a new file ItemController.php to the demo/app/http/controllers/ directory, the code is as follows:

<&#63;php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item as Item;

class ItemController extends Controller {

  private $model;

  public function __construct()
  {
    $this->model = new Item();
  }

  public function showItem($id)
  {
    $users = $this->model->fetchAll();
    echo json_encode($users);
    Log::info('获取用户列表,通过msyql');
  }
}

The new file Item.php in the demo/app/ directory has the following code

<&#63;php namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model {

  protected $fillable = ['name', 'price'];
  protected $guarded = ['id'];

  /**
   * The database table used by the model.
   * default: tbl_items
   * @var string
   */
  // protected $table = 'tbl_items';

  public function fetchAll(){
    $items = $this->all()->toJson();
    return $items;
  }
}

Use a browser to access http://yourIp/item/1 to list all item data

5. Laravel combined with Redis
Direct connection to DB is not enough, database access will soon become the bottleneck of the system. We introduce caching Redis. Still the same idea, let the system run first.
1. Install and start Redis

Installation

$ wget http://download.redis.io/releases/redis-3.0.1.tar.gz
$ tar xzf redis-3.0.1.tar.gz
$ cd redis-3.0.1
$ make

Start

$ src/redis-server

View the official download and installation documentation, just a few commands are needed


2. Install PHP PRedis
PRedis is an extension package for PHP to access redis. You only need to download the original code and there is no need to install PHP extensions (such as php-redis.so). But before that, we need to introduce a composer, because laravel uses it to install third-party packages (manage dependencies).

cd to the path of your App, modify composer.json, add "predis/predis":"~1.0.1" in the require field, then sudo composer update in the current directory, and the package will be automatically downloaded. Required extension packages, these extension packages will be placed in the vendor directory. If there are errors such as insufficient memory, it seems that the reason is insufficient memory allocation. Just restart the server. The complete solution is to modify the server configuration, but I don’t know where to change it. I will add it later

To configure related configurations, just check the official documentation. Mainly configure config/database.php

'redis' => array(
  'cluster' => false,
  'default' => array('host' => '127.0.0.1', 'port' => 6379)
)


3. coding

<&#63;php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User as User;
use Illuminate\Support\Facades\Redis as Redis;

class UserController extends Controller {

  // use User;

  private $model;
  /**
   * Create a new controller instance.
   *
   * @return void
   */
  public function __construct()
  {
    $this->model = new User();
  }

  /**
   * Show 
   *
   * @return Response
   */
  public function showUser($id)
  {
    $redis = Redis::connection('default');
    $cacheUsers = $redis->get('userList');

    if( $cacheUsers ){
      $users = $cacheUsers;
      print_r($users);
      Log::info('获取用户列表,通过redis');
    }else{
      $users = $this->model->fetchAll();
      $redis->set('userList', $users);
      print_r($users);
      Log::info('获取用户列表,通过msyql');
    }
  }
}

Articles you may be interested in:

  • Python uses Redis to implement a job scheduling system (super simple)
  • php method of processing sessions based on redis
  • redis Performance issues of the hGetAll function (remember the annoying HGETALL of Redis)
  • Installation and deployment of Redis under Linux
  • Java connection to redis in Vmware
  • Nginx configuration srcache_nginx module Establishing a cache system with Redis
  • Tutorial on installing and configuring Redis database under CenOS system
  • C Access Redis’s mset binary data interface packaging solution
  • C Developed Redis data import Tool optimization
  • A brief discussion on the coordinated use of Redis in distributed systems

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1113729.htmlTechArticlePHP’s Laravel framework combines the use and deployment of MySQL and Redis databases. Laravelredis is more important than reading the official documents. It is necessary to set up the framework environment. Zero, environment introduction operating system...
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