Download the PHP package alexanderthegreat96/mongo-api-client without Composer
On this page you can find all versions of the php package alexanderthegreat96/mongo-api-client. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download alexanderthegreat96/mongo-api-client
More information about alexanderthegreat96/mongo-api-client
Files in alexanderthegreat96/mongo-api-client
Package mongo-api-client
Short Description Provides a fluid interface with MongoDB API
License MIT
Informations about the package mongo-api-client
MongoDB API Client (PHP)
A PHP client library for interacting with a MongoDB RESTful API, providing a fluent interface for building queries and performing CRUD operations with robust response handling.
Overview
The MongoApiClient
class enables seamless interaction with a MongoDB API server, supporting operations like selecting, inserting, updating, and deleting documents. Key features include:
- Fluent Query Building: Chain methods like
where
,orWhere
,sortBy
,groupBy
for complex queries. - Query Aliases: Use
all
(preferred),select
,get
forfind()
, andfirst
(preferred),firstOrNone
,one
forfirst()
. - Auto-Conversion Control: Toggle type conversion for query values using
autoConvert
inwhere
/orWhere
. - Grouped Data Handling: Process grouped query results with
MongoApiResponseData
, including inner pagination and records. - Pagination Support: Handle pagination metadata via
MongoApiResponsePagination
. - Retry Mechanism: Automatically retry failed requests with configurable exponential backoff.
- Response Wrapping: Normalize API responses into a consistent
MongoApiResponse
envelope. - Iterator and Countable Data:
MongoApiResponseData
supports iteration and counting for flexible data handling.
Installation
Install the package using Composer:
Ensure PHP 8.1+ and the guzzlehttp/guzzle
library are installed (included as a dependency).
Configuration
Configure the client using constructor parameters or environment variables for sensitive data like API keys. Supported environment variables:
MONGO_API_URL
: API server URL (e.g.,api.example.com
).MONGO_API_PORT
: Server port (default:80
).MONGO_API_KEY
: API key for authentication Cage for MongoDB API Client.MONGO_API_SCHEME
: Protocol (http
orhttps
, default:https
).MONGO_API_TIMEOUT
: Request timeout in seconds (default:5.0
).
Example using environment variables:
Usage
Initializing the Client
Create a MongoApiClient
instance with your API server details:
Authentication
The client uses API key authentication by default. Pass the API key in the constructor or via the MONGO_API_KEY
environment variable.
Select Queries
The library provides a powerful fluent interface for select queries, with all()
as the preferred method for fetching multiple documents and first()
for a single document. Use getResult()
to access individual document data for single or multiple results, getRecords()
for grouped query results, and getCount()
for counting documents.
Fetching Multiple Documents
Use all()
(preferred over select()
or get()
) to fetch multiple documents. Iterate through the results and call getResult()
on each:
The autoConvert: true
ensures the age
value is tagged for automatic type conversion (e.g., 18/a
in the query string). The MongoApiResponseData
object is countable, allowing count($data)
.
Fetching a Single Document
Use first()
(preferred over firstOrNone()
or one()
) to retrieve the first matching document. Access the document with getResult()
:
Fetching a Document by ID
Use findById()
to retrieve a document by its _id
and access it with getResult()
:
Using orWhere
with autoConvert
Combine where
and orWhere
for complex queries, using all()
to fetch multiple documents:
Here, age
is tagged for conversion (18/a
), while status
is not (active/n
), preserving the string value.
Grouped Queries with groupBy
Group results by a field (e.g., city
) and use getRecords()
to access records within each group:
The MongoApiResponseData
class provides:
getRecordId()
: The_id
of the group (e.g., thecity
value).getInnerPagination()
: AMongoApiResponsePagination
object for inner pagination metadata.getRecords()
: The list of records in the group.getTotalRecords()
: The total count of records in the group.
Use innerPage
and innerPerPage
(or innerLimit
) to control pagination within groups. The class implements IteratorAggregate
for foreach loops and Countable
for counting records.
Counting Documents
Use count()
to get the number of matching documents. Check isOk()
and call getCount()
:
Pagination Handling
Access pagination metadata for non-grouped or grouped queries:
For grouped queries, use getInnerPagination()
on MongoApiResponseData
for per-group pagination, as shown in the groupBy
example.
Custom Select Queries
Execute custom MongoDB queries or aggregations, using all()
-style result handling:
Use aggregate: true
to execute as a pipeline query.
Other CRUD Operations
Inserting Data
Conditional Inserting
Use insertIf()
to insert a document only if it matches the query conditions:
Updating Data
Updating by ID
Use updateById()
to update a specific document by its _id
:
Deleting Data
Deleting by ID
Use deleteById()
to delete a specific document by its _id
:
Utility Methods
List databases or collections:
Drop databases or collections:
Features
- Fluent Select Queries: Chain
where
,orWhere
,groupBy
,sortBy
, with aliases (all
preferred,select
,get
;first
preferred,firstOrNone
,one
) andautoConvert
control. - Grouped Data Processing:
MongoApiResponseData
providesrecordId
,innerPagination
,records
, andtotalRecords
for grouped results, with iterator and countable support. - Pagination Support:
MongoApiResponsePagination
includescurrentPage
,totalPages
,nextPage
,prevPage
,lastPage
, andperPage
. - Retry Mechanism: Handles transient network failures with exponential backoff via Guzzle.
- Type Safety: Uses strict typing and PHP type declarations for better IDE support.
- Flexible Querying: Supports operators (
=
,!=
,<
,>
,like
, etc.), custom MongoDB queries, and pipeline aggregations. - ID-Based Operations: Supports
findById
,updateById
, anddeleteById
for precise document manipulation. - Result Handling: Use
getResult()
for single/multiple document data andgetRecords()
for grouped query results.
Error Handling
Responses are wrapped in MongoApiResponse
, providing:
isOk()
/isNotOk()
: Check success or failure.getError()
: Error message if failed.getCode()
: HTTP status code (e.g.,400
,401
,429
,500
).getData()
: Documents or grouped data asMongoApiResponseData
.getMessage()
: Additional response message.getRaw()
: Raw API response payload.
Common error codes:
400
: Invalid query or payload.401
: Authentication failure (invalid API key).429
: Rate limit exceeded.500
: Server error.
Example handling errors:
Changelog
Version 1.2.1 (2025-05-18)
- Updated documentation to emphasize
all()
for multiple documents andfirst()
for single documents. - Clarified result handling: use
getResult()
for single/multiple results,getRecords()
for grouped data, andgetCount()
for counting. - Standardized examples to use
isOk()
andfromCollection()
consistently. - Removed OAuth references as they are not supported in the current codebase.
Version 1.2.0 (2025-05-18)
- Added
isOk()
,isNotOk()
,getRaw()
, andgetMessage()
toMongoApiResponse
. - Enhanced
MongoApiResponseData
withIteratorAggregate
,Countable
,getRecordId()
,getResults()
, andgetResult()
. - Added
findById()
,insertIf()
,updateById()
,deleteById()
, andinnerLimit()
toMongoApiClient
. - Added
getNextPage()
,getPrevPage()
,getLastPage()
, andgetPayload()
toMongoApiResponsePagination
. - Improved type safety and PHPDoc annotations.
- Updated terminology to use “collection” instead of “table” for MongoDB consistency.
Version 1.1.0 (2025-05-18)
- Added support for environment variable configuration.
- Enhanced
executeCustomQuery
with complex aggregation examples. - Improved error handling with specific error code documentation.
Version 1.0.0
- Initial release with fluent query building, CRUD operations, grouped data handling, and pagination support.
License
This project is licensed under the MIT License. See the LICENSE
file for details.