如何设置Laravel 5.2连接到API [英] How to set up Laravel 5.2 to connect to API

查看:68
本文介绍了如何设置Laravel 5.2连接到API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个后端C ++应用程序,它使用标准TCP连接接收JSON请求.该应用程序管理所有业务逻辑(用户身份验证,事务处理,数据请求和验证).

I have a backend C++ application that receives JSON requests using a standard TCP connection. This application manages all the business logic (user authentication, transaction processing, data requests and validation).

我如何设置Laravel 5.2以连接到该服务器以进行用户身份验证以及事务处理?我不需要Laravel端的任何数据库,因为所有数据都可以通过C ++应用程序进行访问.

How do I need to setup Laravel 5.2 to connect to this server for user authentication and also transaction processing? I do not need any database on the Laravel side as all the data will be accessed through the C++ application.

作为奖励,如果可能的话,我还希望将JWT纳入用户身份验证部分.

As a bonus, I would also like to incorporate JWT for the user authentication part if that will be possible.

下面的代码是我当前使用标准PHP连接到应用程序服务器的方式.我想要相同的功能,但使用的是Laravel方式.

The code below is the way I currently connect to the application server using standard PHP. I want the same functionality but in a more Laravel way.

class tcp_client
{
    private $sock;

    function __construct()
    {
        // create the socket
        $this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!is_resource($this->sock))
        {
            // throw exception
        }

        // set socket options
        $this->set_options();
    }

    function connect($host, $port)
    {
        $timeout = 3;
        $startTime = time();
        while (!socket_connect($this->sock, $host, $port))
        {
            if ((time() - $startTime ) >= $timeout)
            {
                // throw exception
            }
            sleep(1);
        }
    }

    private function set_options()
    {
        if (!socket_set_option($this->sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 5,
                    'usec' => 0)))
        {
            // throw exception
        }

        if (!socket_set_option($this->sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5,
                    'usec' => 0)))
        {
            // throw exception
        }
    }

    public function request($request)
    {
        // the first 6 characters will indicate the length of the JSON string
        $request = str_pad(strlen($request), 6, '0', STR_PAD_LEFT) . $request;

        //Send the message to the server
        if (!socket_send($this->sock, $request, strlen($request), 0))
        {
            // throw exception
        }

        //Now receive header from server
        $header = 0;
        if (socket_recv($this->sock, $header, 6, MSG_WAITALL) === FALSE)
        {
            // throw exception
        }  

        //Now receive body from server
        $body = "";
        if (socket_recv($this->sock, $body, $header, MSG_WAITALL) === FALSE)
        {
            // throw exception
        }

        return $body;
    }

}

推荐答案

我已经通过模仿DatabaseUserProvider设法自行解决了这个问题.

I have managed to sort this out on my own by mimicking the DatabaseUserProvider.

  1. 使用子文件夹App\Blah\AuthApp\Blah\TCP

创建新的用户提供程序

> php artisan make:provider App\Blah\Auth\BlahUserProvider

  • \vendor\laravel\framework\src\Illuminate\Auth\DatabaseUserProvider.php的内容复制到新的提供程序(BlahUserProvider.php),并将类名称更改回BlahUserProvider.

  • Copied the contents of \vendor\laravel\framework\src\Illuminate\Auth\DatabaseUserProvider.php to the new provider (BlahUserProvider.php) and changed the class name back to BlahUserProvider.

    创建了App\Blah\TCP\TCPClient.php并将我的问题中类的内容复制到了该文件中.

    Created App\Blah\TCP\TCPClient.php and copied the contents of the class in my question to this file.

    更改名称空间,并在BlahUserProvider.php

    namespace App\Blah\Auth;
    use App\Blah\TCP\TCPClient;
    use stdClass;
    

  • BlahUserProvider中的功能retrieveByCredentials的内容替换为

  • Replaced the contents of function retrieveByCredentials in BlahUserProvider with

    public function retrieveByCredentials(array $credentials)
    { 
      $tcp_request = "{\"request\":\"login\","
                   . "\"email\":\"" . $credentials['email'] . "\","
                   . "\"password\":\"" . $credentials['password'] . "\"}";
    
      $tcp_result = json_decode(str_replace("\n","\\n",$this->conn->request($tcp_request)), true);
    
      $user = new stdClass();
      $user->id = $tcp_result['user']['id'];
      $user->name = $tcp_result['user']['name'];
    
      return $this->getGenericUser($user);
    }
    

  • 我现在还用与功能retrieveByCredentials相同的内容替换了功能retrieveById,只是因为我仍然必须在C ++应用程序中创建请求,所以用户可以登录.

  • I also replaced function retrieveById with the same contents as function retrieveByCredentials for now just so the user can log in because I still have to create the request in the C++ application.

    扩展了\vendor\laravel\framework\src\Illuminate\Auth\CreatesUserProviders.php中的createUserProvider函数以包括我的新驱动程序,并且还添加了函数createBlahProvider

    Extended the createUserProvider function in \vendor\laravel\framework\src\Illuminate\Auth\CreatesUserProviders.php to include my new driver and also added function createBlahProvider

    public function createUserProvider($provider)
    {
      $config = $this->app['config']['auth.providers.' . $provider];
    
      if (isset($this->customProviderCreators[$config['driver']]))
      {
        return call_user_func(
                $this->customProviderCreators[$config['driver']], $this->app, $config
        );
      }
    
      switch ($config['driver'])
      {
        case 'database':
            return $this->createDatabaseProvider($config);
        case 'eloquent':
            return $this->createEloquentProvider($config);
        case 'blah':
            return $this->createBlahProvider($config);
        default:
            throw new InvalidArgumentException("Authentication user provider [{$config['driver']}] is not defined.");
      }
    }
    
    protected function createBlahProvider($config)
    {
      $connection = new \App\Blah\TCP\TCPClient();
      return new \App\Blah\Auth\BlahUserProvider($connection, $this->app['hash'], $config['model']);
    }
    

  • config\auth.php中的提供程序更改为非用户提供程序

  • Changed the provider in config\auth.php to the blah user provider

    'providers' => [
      'users' => [
        'driver' => 'blah',
        'model' => App\User::class,
    ],
    

  • 这篇关于如何设置Laravel 5.2连接到API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆