Experience of the composer Ratchet Experiment

Source: Internet
Author: User
Tags autoload composer install

Introduction

Composer is a tool used in PHP to manage dependencies. You can declare the dependent external library (Libraries) in your project. composer will help you install these dependent library files.

Dependency Management

Composer is not a package manager. Of course, it processes packages and libraries. You can think that composer is the cornerstone of a project and Package) put it under a directory (such as vendor). By default, it will not install anything global. It is just a management tool.

This idea comes from node NPM and Ruby bundler, but it is not exactly the same as PHP.

In PHP, composer mainly solves the following problems:

  1. There are many library files under your project

  2. These libraries are mutually dependent.

  3. These are very dependent on you.

  4. Composer can find out which version of the package you want to install, and then install them

Declare mutual relationship

Suppose you have created a project, you need a library and record them, and then you decide to use monolog. Now we add a file named composer. JSON in our project to describe the project's interrelationships.

Basic use of composer:

For example, to load Ratchet

Use the composer and require keywords in the project:

Add the following code to the composer. JSON (under the project root directory) file:

{    "require": {        "cboden/ratchet": "0.3.*"    }}

As you can see, the require object will map the package name (cboden/Ratchet) and package version to 1. 0 .*

Installation Package

Composer install

About automatic loading:

To facilitate the loading of package files, composer automatically generates a file named "vendor/autoload. php". You can only use it wherever you need it.

require ‘vendor/autoload.php‘;

This means that you can use third-party code very conveniently. If your project needs to use monlog, you can directly use it. They have all loaded it automatically!

Of course, you can also load your code in composer. JSON:

{    "autoload": {        "psr-0": {"Acme": "src/"}    }}

 

Composer will register the psr-0 as an Acme namespace

You can define a ing to the file directory through the namespace. the src directory is your root directory, and the vendor directory is at the same level. For example, a file is src/Acme/Foo. PHP contains the Acme \ Foo class.

After you add autoload, you must re-install it to generate the file vendor/autoload. php.

When we reference this file, we will return the strength of an autoloader class, so you can put the returned value into a variable and then add more namespaces, this is very convenient in the development environment, for example:

$loader = require ‘vendor/autoload.php‘;$loader->add(‘Acme\Test‘, __DIR__);

------------------------------------------------------ The split line describes the role of composer, because the loading of ratchat classes relies on it to simplify compaction --------------------------------------------------------------

The following describes how to set up Ratchet (I set up it in Windows 7)

1. Create a project root directory

Create composer. JSON in the root directory:

{    "require": {        "cboden/ratchet": "0.3.*"    }}

2. Execute the doscommand in the root directory:

》composer install

3. Create your own MyApp file. Before creating a namespace, you must modify composer. JSON:

{    "autoload": {        "psr-0": {            "MyApp": "src"        }    },    "require": {        "cboden/ratchet": "0.3.*"    }}

Install:

>>composer install

4. Create your own chat room application class. This class listens to four events: Close, send messages, enable, and error. The code of the class is as follows (this class will be modified later ):

<?phpnamespace MyApp;use Ratchet\MessageComponentInterface;use Ratchet\ConnectionInterface;class Chat implements MessageComponentInterface {    public function onOpen(ConnectionInterface $conn) {    }    public function onMessage(ConnectionInterface $from, $msg) {    }    public function onClose(ConnectionInterface $conn) {    }    public function onError(ConnectionInterface $conn, \Exception $e) {    }}

Save:/Src/MyApp/chat. php

5. Create a class to run the socket service:

<?phpuse Ratchet\Server\IoServer;use MyApp\Chat;    require dirname(__DIR__) . ‘/vendor/autoload.php‘;    $server = IoServer::factory(        new Chat(),        8080    );    $server->run();

Save:// Bin/chat-server.php

Execute this script in DOS to enable the Service:

php bin/chat-server.php

6. So far, our server has been enabled by script and the chat class has been executed. Now we need to add code to the chat class:

<?phpnamespace MyApp;use Ratchet\MessageComponentInterface;use Ratchet\ConnectionInterface;class Chat implements MessageComponentInterface {    protected $clients;    public function __construct() {        $this->clients = new \SplObjectStorage;    }    public function onOpen(ConnectionInterface $conn) {        // Store the new connection to send messages to later        $this->clients->attach($conn);        echo "New connection! ({$conn->resourceId})\n";    }    public function onMessage(ConnectionInterface $from, $msg) {        $numRecv = count($this->clients) - 1;        echo sprintf(‘Connection %d sending message "%s" to %d other connection%s‘ . "\n"            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? ‘‘ : ‘s‘);        foreach ($this->clients as $client) {            if ($from !== $client) {                // The sender is not the receiver, send to each client connected                $client->send($msg);            }        }    }    public function onClose(ConnectionInterface $conn) {        // The connection is closed, remove it, as we can no longer send it messages        $this->clients->detach($conn);        echo "Connection {$conn->resourceId} has disconnected\n";    }    public function onError(ConnectionInterface $conn, \Exception $e) {        echo "An error has occurred: {$e->getMessage()}\n";        $conn->close();    }}

7. Open three terminals to run the experiment through the win DOS window:

》》php bin/chat-server.php

 

》》telnet localhost 8080
telnet localhost 8080

Print hellow world in each terminal, and the other terminal will also appear!

8. Now we have succeeded in the terminal experiment. The next step is how to experiment in the browser. You still need to modify the chat class:

<?phpuse Ratchet\Server\IoServer;use Ratchet\Http\HttpServer;use Ratchet\WebSocket\WsServer;use MyApp\Chat;    require dirname(__DIR__) . ‘/vendor/autoload.php‘;    $server = IoServer::factory(        new HttpServer(            new WsServer(                new Chat()            )        ),        8080    );    $server->run();

DOS execute this class PHP./bin/chat-server.php

9. Open several browsers to do experiments. Use the console to execute the following JS Code:

var conn = new WebSocket(‘ws://localhost:8080‘);conn.onopen = function(e) {    console.log("Connection established!");};conn.onmessage = function(e) {    console.log(e.data);};

When you see "Connection established! "It indicates that you have successfully connected. At this time, you can send a message to another browser!

conn.send(‘Hello World!‘);

Try it! You will succeed! I used three browsers to perform experiments. The results are as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.