Skip to content
ffb255 edited this page Mar 6, 2020 · 2 revisions

When you are trying to build an in-production chatbot, you need a conversation. As you know, conversation logics defined in a PHP class. So what happens if you need an external variable like a Database Connection? Inject is a pure class with dynamic methods, which help you to pass a variable from outside of the conversation logic class to a step method.

Quick Start

Look at the example below.

use ffb255\Botter\BotterFactory;
use ffb255\Botter\Updates\Events\On;
use ffb255\Botter\Conversations\Conversation;

class SignupConversation extends Conversation
{
    public function start()
    {
        $this->say("You are signing up in botter! Enter your email address:");
        $this->next("finishSignup");
    }

    public function finishSignup()
    {
        // Inserting user to DB
        // We need a db connection! So how you can access $db variable?
        $this->say("Thank you. you are signed up successfully.");
        $this->finish();
    }
}

$config = [
    'token' => 'YOUR_BOT_TOKEN',
];
$botter = BotterFactory::create($config);

// DB is our testing database connection
$db = Database::createInstace("host", "myuser", "mypass");

On::text('/signup', function() use($botter){
    $botter->startConversation(new SignupConversation);     
});

$botter->listen();

Assume that you need $db in your finishStep() method in conversation logic class. You can easily pass your variable to Inject class and retrieve them in your step method.

use ffb255\Botter\Conversations\Inject;
Inject::databaseConnection($db);

So when you call Inject::databaseConnection() anywhere you want, botter return your $db as output. Let's fix our previous example:

use ffb255\Botter\BotterFactory;
use ffb255\Botter\Updates\Events\On;
use ffb255\Botter\Conversations\Conversation;
use ffb255\Botter\Conversations\Inject;

class SignupConversation extends Conversation
{
    public function start()
    {
        $this->say("You are signing up in botter! Enter your email address:");
        $this->next("finishSignup");
    }

    public function finishSignup()
    {
        // Inserting user to DB
        $db = Inject::databaseConnection();
        $db->insert();
        
        $this->say("Thank you. you are signed up successfully.");
        $this->finish();
    }
}

$config = [
    'token' => 'YOUR_BOT_TOKEN',
];
$botter = BotterFactory::create($config);

// DB is our testing database connection
$db = Database::createInstace("host", "myuser", "mypass");

On::text('/signup', function() use($botter){
    $botter->startConversation(new SignupConversation);     
});

Inject::databaseConnection($db);
$botter->listen();

Clone this wiki locally