Analysis of ThinkPhp5 | E-commerce Module

Posted by AncientSage on Sat, 15 Jun 2019 23:45:50 +0200

ThinkPhp5 framework is a lightweight development framework based on MVC. Its modular construction is simple and effective. Compared with previous versions, it is a subversive change. In this paper, combined with the common functions of some websites, a brief analysis of the basic principles, a small test knife.

Compared with the complete development manual of ThinkPhp 5.0, the Quick Start of ThinkPhp 5 is more suitable for fast learning, mastering its main components and opening up the whole picture.

I. Login Module

  • Fill in the login username and password, and jump after successful login; close the page and log in again within a certain period of time, without re-login, jump directly; the reason is that the server saves session containing the user's information.

Baidu Nuomi Login.png
// Sign in
public function login()
{
        // Logon checks whether user session exists, there is a direct jump page, and there is no continued login
        $user = session('o2o_user','', 'o2o'); 
        if($user && $user->id) {
           $this->redirect(url('index/index'));
        }
        return $this->fetch();
}
// Logon Detection
public function logincheck() 
{
        //Determine whether it is a post form request
        if(!request()->isPost()) {
           $this->error('Illegal submission');
        }
       //Get form data
        $data = input('post.');
       //Model-based Access to User Data
        try {
            $user = model('User')->getUserByUsername($data['username']);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
       //The user does not exist or the user does not exist in a state of 1
        if(!$user || $user->status != 1) {
            $this->error('The user does not exist');
        }
        // Based on salt strings, md5 encrypts to determine passwords
        if(md5($data['password'].$user->code) != $user->password) {
            $this->error('Incorrect password');
        }
        // Logon success, update user logon time
        model('User')->updateById(['last_login_time'=>time()], $user->id);
        //Record user information to session
        session('o2o_user', $user, 'o2o');
        $this->success('Successful login', url('index/index'));
}

II. Verification Code Mechanism

  • Verification codes in ThinkPhp5 are flexible to use. Learn to use them. Refer to the manual specifically.
//1 - Compooser relies on management tools to install validation code class libraries and automatically install them into vendor folders
composer require topthink/think-captcha
//2 - Call the helper function captcha_img() on the page
<input type="text" name="verifycode" placeholder="Please enter the verification code.">
<div>{:captcha_img()}</div>
//3 - Implement verification code in the background and call the helper function captcha_check()
if(!captcha_check($data['verifycode'])) {
      // Check failure
      $this->error('Verification code incorrect');
}
//4 - Realize click auto refresh of validation code picture
$js_src = "this.src='".captcha_src()."'";
return '![](' . captcha_src($id) . ')';
//5 - The helper function is located in helper.php under the vendor folder

3. Ajax Asynchronous Data Acquisition

  • Ajax is widely used for a small amount of data interaction in the background server. Take the registration information we often fill in as an example, click on the left side, and update the data automatically on the right side.

Click on the left and update automatically on the right.png
$(".cityId").change(function(){
    //Get the value of class cityId
    city_id = $(this).val();
    //This is the request address thrown to the back-end server
    url = SCOPE.city_url;
    //Assemble data
    postData = {'id':city_id};
    $.post(url,postData,function(result){
        //If the function returns successfully, the information is assembled and the html is filled.
        if(result.status == 1) {
            // Fill information in html
            data = result.data;
            city_html = "";
            $(data).each(function(i){
                city_html += "<option value='"+this.id+"'>"+this.name+"</option>";
            });
            $('.se_city_id').html(city_html);
        }else if(result.status == 0) {
            $('.se_city_id').html('');
        }
    }, 'json');
});

IV. Picture upload

  • Based on the file upload mechanism of ThinkPhp5 and with the help of uplodify plug-in, the image upload function is realized. uplodify plug-in learning.

Picture upload.png
$(function() {
    $("#file_upload").uploadify({
        'swf'             : SCOPE.uploadify_swf,
        //Automatically jump to the address'{: url('api/image/upload')}'
        'uploader': SCOPE.image_upload,
        'buttonText'      : 'Picture upload',
        'fileTypeDesc'    : 'Image files',
        'fileObjName'     : 'file',
        'fileTypeExts'    : '*.gif; *.jpg; *.png',
        'onUploadSuccess' : function(file, data, response) {
            console.log(file);
            console.log(data);
            console.log(response);
            if(response) {
                var obj = JSON.parse(data);
                // Fill the returned data into the page
                $("#upload_org_code_img").attr("src", obj.data);
                $("#file_upload_image").attr("value", obj.data);
                $("#upload_org_code_img").show();
            }
        }
    });
// Processing Logic of Back-end Jump Address
public function upload() {
        //Instantiate a file object
        $file = Request::instance()->file('file');
        // Given a file directory for image storage
        $info = $file->move('upload');
        if($info && $info->getPathname()) {
            return show(1, 'success','/'.$info->getPathname());
        }
        return show(0,'upload error');
    }

V. Front-end verification

  • In the merchant's commodity details page, there is a choice of purchase quantity. There are front-end verification and dynamic pages, as follows:

Front-end Quantity Check.png
//1-If you enter non-numeric content in the number box, automatically thinner than 1
//2-If the number is 1, the number'-'button on the left will fail.

// Determine whether it is a positive integer
function isNaN(number){
    var reg = /^[1-9]\d*$/;
    return reg.test(number);
  }
// Event change mechanism
  function inputChange(num){
    // If it is not a positive integer, it will automatically be 1
    if(!isNaN(num)){
      $(".buycount-ctrl input").val("1");
    }
   // If it is a positive integer, the original value is preserved.
    else{
      $(".buycount-ctrl input").val(num);
      // If the value is 1, the left style will be invalidated by automatic filtering.
      if(num == 1){
        $(".buycount-ctrl a").eq(0).addClass("disabled");
      }
     // Value not 1, left style is valid
      else{
        $(".buycount-ctrl a").eq(0).removeClass("disabled");
      }
    }
  }
  $(".buycount-ctrl input").keyup(function(){
    var num = $(".buycount-ctrl input").val();
    inputChange(num);
  });
  $(".minus").click(function(){
    var num = $(".buycount-ctrl input").val();
    num--;
    inputChange(num);
  });
  $(".plus").click(function(){
    var num = $(".buycount-ctrl input").val();
    num++;
    inputChange(num);
  });

6. Baidu Map Loading

  • In the group buying websites such as Mei Tuan and Nuomi, as well as in the fast train software such as Droplet and Uber, you can always see a lot of map loading. Simply learn to use some Baidu map interface to load address pictures. Use of Geocoding API Click to see.

Baidu Map Loading.png
public static function staticimage($center) {
        if(!$center) {
            return '';
        }
       // Provided by configuration file
        $data = [
            'ak' => config('map.ak'),
            'width' => config('map.width'),
            'height' => config('map.height'),
            'center' => $center,
            'markers' => $center,
        ];
        $url = config('map.baidu_map_url').config('map.staticimage').'?'.http_build_query($data);
        $result = doCurl($url);
        return $result;
    }
// Provided by common.php file
function doCurl($url, $type=0, $data=[]) {
    $ch = curl_init(); // Initialization
    // set an option
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER,0);

    if($type == 1) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //Execute and retrieve content
    $output = curl_exec($ch);
    // Release curl handle
    curl_close($ch);
    return $output;
}

Come here and rest for a while. Today's weather, a little breeze in the sunshine, or very suitable for going out. Happy weekend when you go out to enjoy yourself.

Topics: Session PHP JSON curl