You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Here I assume, that composer command is available in the PATH. To check that, try to display its version:
$ composer --version
Composer version 2.2.7 2022-02-25 11:12:27
Now, lets create new project. Here I'm going to use [Slim framework][slim-home], as one of the many minimalistic PHP web
framework avaialble in the ecosystem.
And run composer update to lock the change in composer.lock.
The default Slim skeleton uses InMemoryUserRepository as an implementation of the persistence. Lets replace it with
class, that will keep user records in Couchbase.
Create src/Infrastructure/Persistence/User/CouchbaseUserRepository.php with the following content:
<?phpdeclare(strict_types=1);
namespaceApp\Infrastructure\Persistence\User;
useApp\Domain\User\User;
useApp\Domain\User\UserNotFoundException;
useApp\Domain\User\UserRepository;
useCouchbase\Exception\DocumentNotFoundException;
useCouchbase\Scope;
useCouchbase\Collection;
class CouchbaseUserRepository implements UserRepository
{
privateScope$scope;
privateCollection$collection;
/** * @param Scope $scope */publicfunction__construct(Scope$scope)
{
$this->scope = $scope;
// we use default collection for brevity here, but it could be any other existing collection$this->collection = $this->scope->collection("_default");
}
/** * {@inheritdoc} */publicfunctionfindAll(): array
{
$result = $this->scope->query('SELECT * FROM _default u ORDER BY id');
returnarray_map(function ($row) {
$document = $row['u'];
returnnewUser($document['id'], $document['username'], $document['firstName'], $document['lastName']);
}, $result->rows());
}
/** * {@inheritdoc} */publicfunctionfindUserOfId(int$id): User
{
try {
$result = $this->collection->get(strval($id));
} catch (DocumentNotFoundException$exception) {
thrownewUserNotFoundException();
}
$document = $result->content();
returnnewUser($document['id'], $document['username'], $document['firstName'], $document['lastName']);
}
}
Couchbase is new dependency for the application, so it have to be registered in application container. I decided to
register it as Couchbase\Scope::class, becase I'm going to keep all data for the application in the same scope.
Again, for simplicity in my case, I don't specify name of the scope here, because the repository is going to use default
scope, but in real-world application, the scope name should be also set in the configuration.
Now, update app/dependencies.php, where we will create connection to Couchbase using credentials from the settings,
and open default scope of the given bucket:
diff --git i/app/dependencies.php w/app/dependencies.php
index 9a948b5..05973cb 100644
--- i/app/dependencies.php+++ w/app/dependencies.php@@ -8,6 +8,7 @@ use Monolog\Logger;
use Monolog\Processor\UidProcessor;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
+use Couchbase\Scope;
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
@@ -26,4 +27,20 @@ return function (ContainerBuilder $containerBuilder) {
return $logger;
},
]);
++ $containerBuilder->addDefinitions([+ Scope::class => function (ContainerInterface $c) {+ $settings = $c->get(SettingsInterface::class);++ $couchbaseSettings = $settings->get('couchbase');++ $clusterOptions = new Couchbase\ClusterOptions();+ $clusterOptions->credentials($couchbaseSettings['username'], $couchbaseSettings['password']);++ $cluster = new Couchbase\Cluster($couchbaseSettings['connectionString'], $clusterOptions);+ $scope = $cluster->bucket($couchbaseSettings['bucket'])->defaultScope();++ return $scope;+ },+ ]);
};
And the last step is to replace in-memory implementation of the User repository with the one we mentioned previously:
diff --git i/app/repositories.php w/app/repositories.php
index 62a58f3..3bb7cbf 100644
--- i/app/repositories.php+++ w/app/repositories.php@@ -2,12 +2,12 @@
declare(strict_types=1);
use App\Domain\User\UserRepository;
-use App\Infrastructure\Persistence\User\InMemoryUserRepository;+use App\Infrastructure\Persistence\User\CouchbaseUserRepository;
use DI\ContainerBuilder;
return function (ContainerBuilder $containerBuilder) {
- // Here we map our UserRepository interface to its in memory implementation+ // Here we map our UserRepository interface to its Couchbase implementation
$containerBuilder->addDefinitions([
- UserRepository::class => \DI\autowire(InMemoryUserRepository::class),+ UserRepository::class => \DI\autowire(CouchbaseUserRepository::class)
]);
};
That's all we need. Let's verify it now. Because the application provides read-only API, the users have to be created
manually or by some other tool. The easiest way would be Couchbase Web UI. Create there couple for JSON documents like
this:
Ah, so couchbase/couchbase 4.0 is now published on packagist: https://packagist.org/packages/couchbase/couchbase, so I can pull it with composer.
This wasn't the case when we released, so probably explains why I couldn't pull it.
Getting Started with Couchbase and Composer
In this small note, I demonstrate how to use Couchbase PHP SDK with Composer.
Here I assume, that
composer
command is available in the PATH. To check that, try to display its version:Now, lets create new project. Here I'm going to use [Slim framework][slim-home], as one of the many minimalistic PHP web
framework avaialble in the ecosystem.
This command will create new directory
couchbase-demo
with skeleton of the project.Now navigate in the terminal to the directory and try to start webserver
Default application will respond with
"Hello world!"
message:Lets add Couchbase SDK to the project. To do so, first we need to install the SDK in the system, SDK
documentation describes it in details.
Once SDK installed, it should be displayed in the list of modules:
Next step is to update
composer.json
in the project.And run
composer update
to lock the change incomposer.lock
.The default Slim skeleton uses
InMemoryUserRepository
as an implementation of the persistence. Lets replace it withclass, that will keep user records in Couchbase.
Create
src/Infrastructure/Persistence/User/CouchbaseUserRepository.php
with the following content:Couchbase is new dependency for the application, so it have to be registered in application container. I decided to
register it as
Couchbase\Scope::class
, becase I'm going to keep all data for the application in the same scope.Add new section to the
app/settings.php
Again, for simplicity in my case, I don't specify name of the scope here, because the repository is going to use default
scope, but in real-world application, the scope name should be also set in the configuration.
Now, update
app/dependencies.php
, where we will create connection to Couchbase using credentials from the settings,and open default scope of the given bucket:
And the last step is to replace in-memory implementation of the User repository with the one we mentioned previously:
That's all we need. Let's verify it now. Because the application provides read-only API, the users have to be created
manually or by some other tool. The easiest way would be Couchbase Web UI. Create there couple for JSON documents like
this:
id:
"1"
value:
id:
"2"
value:
Start the server:
Make few requests with cURL:
The text was updated successfully, but these errors were encountered: