paint-brush
Evaluating Swoft — A PHP Microservices Frameworkby@inhere
978 reads
978 reads

Evaluating Swoft — A PHP Microservices Framework

by inhereAugust 21st, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Swoft is a PHP high performance microservice co-routine framework. It has been published for many years and has become the best choice for PHP. It can be like Go and is resident in memory independent of traditional PHP-FPM. There are similar Go language operations, similar to the Spring Cloud framework flexible annotations. It is compatible with Laravel ORM, It’s easy for PHP developer to use in Swoft. It's easy to define a high-performance connection pool with like this:

Company Mentioned

Mention Thumbnail
featured image - Evaluating Swoft — A PHP Microservices Framework
inhere HackerNoon profile picture

Swoft is a PHP high performance microservice co-routine framework.

It has been published for many years and has become the best choice for php. It can be like Go, built-in co-routine web server and common co-routine client and is resident in memory, independent of traditional PHP-FPM.

There are similar Go language operations, similar to the Spring Cloud framework flexible annotations.

Github

https://github.com/swoft-cloud/swoft

Feature

Full Co-routine Framework

Swoft is first PHP resident in memory annotation framework, with Spring Boot conventions larger than the configuration design concept, with a set of development specifications.

AOP

AOP is an object oriented programming that makes it easier to decouple business code, improve code quality, and increase code reusability.

/**
 * @Aspect(order=1)
 * @PointBean(include={"App\Http\Controller\TestExecTimeController"})
 */
class CalcExecTimeAspect
{
    protected $start;

    /**
     * @Before()
     */
    public function before()
    {
        $this->start = microtime(true);
    }

    /**
     * @After()
     */
    public function after(JoinPoint $joinPoint)
    {
        $method = $joinPoint->getMethod();
        $after = microtime(true);
        $runtime = ($after - $this->start) * 1000;

        echo "{$method} cost: {$runtime}ms\n";
    }
}

Http Service

Http service is simple and flexible, only to use @Controller() and @RequestMapping(route="index") annotations to define service.

/**
 * @Controller()
 */
class IndexController
{
    /**
     * @RequestMapping(route="index")
     */
    public function index(): string
    {
        return "test";
    }
}

WebSocket service

Swoft provides a complete Websocket for developers to quickly build service

/**
 * @WsModule(
 *     "/chat",
 *     messageParser=TokenTextParser::class,
 *     controllers={HomeController::class}
 * )
 */
class ChatModule
{
    /**
     * @OnOpen()
     * @param Request $request
     * @param int     $fd
     */
    public function onOpen(Request $request, int $fd): void
    {
        server()->push($request->getFd(), "Opened, welcome!(FD: $fd)");
    }
}

RPC Service

Swoft RPC can be called like a native function as Dubbo.

/**
 * @Controller()
 */
class RpcController
{
    /**
     * @Reference(pool="user.pool", version="1.0")
     *
     * @var UserInterface
     */
    private $userService;

    /**
     * @RequestMapping("getList")
     *
     * @return array
     */
    public function getList(): array
    {
        $result  = $this->userService->getList(12, 'type');
        return [$result];
    }
}

TCP Service

Swoft also provides feature-rich TCP service support.

<?php declare(strict_types=1);

namespace App\Tcp\Controller;

use Swoft\Tcp\Server\Annotation\Mapping\TcpController;
use Swoft\Tcp\Server\Annotation\Mapping\TcpMapping;
use Swoft\Tcp\Server\Request;
use Swoft\Tcp\Server\Response;

/**
 * Class DemoController
 *
 * @TcpController()
 */
class DemoController
{
    /**
     * @TcpMapping("echo", root=true)
     * @param Request  $request
     * @param Response $response
     */
    public function echo(Request $request, Response $response): void
    {
        // $str = $request->getRawData();
        $str = $request->getPackage()->getDataString();

        $response->setData('[echo]hi, we received your message: ' . $str);
    }
}

Connection pool

Swoft is simple to define a high-performance connection pool with like this:

return [
    'xxx.pool' => [
        'class'       => \Swoft\xxx\Pool::class,
        'minActive'   => 10,
        'maxActive'   => 20,
        'maxWait'     => 0,
        'maxWaitTime' => 0,
        'maxIdleTime' => 60,
    ]
];

Compatible with Laravel ORM

Swoft database is highly compatible with Laravel ORM, It’s easy for PHP developer to use in Swoft.

// Model
$user = User::new();
$user->setName('name');
$user->setSex(1);
$user->setDesc('this my desc');
$user->setAge(mt_rand(1, 100));
$user->save();
$id = $user->getId();

// Query
$users = DB::table('user')->get();
foreach ($users as $user) {
    echo $user->name;
}

// Transaction
DB::beginTransaction();
$user = User::find($id);
$user->update(['name' => $id]);

DB::beginTransaction();
User::find($id)->update(['name'=>'sakuraovq']);
DB::rollBack();

DB::commit();

Microservice

Swoft provides a set of quick build microservice governance components, it’s easy for developers to use.

Service Registration and DiscoveryService BrokerCentralized ConfigurationService Throttling ability

/**
 * @Bean()
 */
class Test
{
    /**
     * @Breaker(fallback="funcFallback")
     *
     * @return string
     * @throws Exception
     */
    public function func(): string
    {
        // Do something

        throw new Exception('Breaker exception');
    }

    /**
     * @RequestMapping()
     * @RateLimiter(key="request.getUriPath()")
     *
     * @param Request $request
     *
     * @return array
     */
    public function requestLimiter(Request $request): array
    {
        $uri = $request->getUriPath();
        return ['requestLimiter', $uri];
    }
}

Github

https://github.com/swoft-cloud/swoft