The perfect starting point to integrate Algolia within your PHP project

Overview

Algolia for PHP

The perfect starting point to integrate Algolia within your PHP project

CircleCI Total Downloads Latest Version License

DocumentationLaravelSymfonyCommunity ForumStack OverflowReport a bugFAQSupport

Features

  • Thin & minimal low-level HTTP client to interact with Algolia's API
  • Supports php ^7.2.

💡 Getting Started

First, install Algolia PHP API Client via the composer package manager:

composer require algolia/algoliasearch-client-php

Then, create objects on your index:

$client = Algolia\AlgoliaSearch\SearchClient::create(
  'YourApplicationID',
  'YourAdminAPIKey'
);

$index = $client->initIndex('your_index_name');

$index->saveObjects(['objectID' => 1, 'name' => 'Foo']);

Finally, you may begin searching a object using the search method:

$objects = $index->search('Fo');

For full documentation, visit the Algolia PHP API Client.

Troubleshooting

Encountering an issue? Before reaching out to support, we recommend heading to our FAQ where you will find answers for the most common issues and gotchas with the client.

Use the Dockerfile

If you want to contribute to this project without installing all its dependencies, you can use our Docker image. Please check our dedicated guide to learn more.

📄 License

Algolia PHP API Client is an open-sourced software licensed under the MIT license.

Comments
  • PHP 8 Support

    PHP 8 Support

    | Q | A | ----------------- | ---------- | Bug fix? | no | New feature? | yes | BC breaks? | no
    | Related Issue | Fix #... | Need Doc update | no

    Describe your change

    This PR will provide PHP 8 Support for the library. Atm this is blocking https://github.com/laravel/scout/pull/425

    I'll keep the PR in draft until I've fixed the build.

    opened by driesvints 37
  • Fix - Unescaped Unicode JSON encoding

    Fix - Unescaped Unicode JSON encoding

    | Q | A | ----------------- | ---------- | Bug fix? | yes | New feature? | no | BC breaks? | no
    | Related Issue | Fix #546 | Need Doc update | no

    Describe your change

    Automatically enable JSON_UNESCAPED_UNICODE option for request payload encoding.

    I've tested this on a real index an it does work as expected — the document is indexed perfectly fine.

    This is a port of #545 onto 2.x master version. Reincarnation of #577 with a unit test added.

    opened by e1himself 17
  • [Testing] Tests fails for PRs due to missing applicationId env variable.

    [Testing] Tests fails for PRs due to missing applicationId env variable.

    I have some work in progress over here: #62 The problem is that travis does not seem to be aware of any applicationId, and I suppose the apiKey is not injected either.

    Locally everything works fine, is there a trick here to tell travis about my custom appId and apiKey so my tests turn to green?

    opened by rayrutjes 17
  • Keep state between processes

    Keep state between processes

    We abstracted an interface for the failed hosts retrieval so that users can easily choose their caching strategy based on what is best according to their environment.

    By default we push the new File Based cache strategy, but if the tmp directory is not writable, we fallback to the in memory strategy.

    User can provide an implementation of FailingHostsCache as a replacement of this strategy.

    Because of the current design of the Client, the FailingHostsCache implementation needs to be provided at Client initialization because that is where the ClientContext is instantiated and during that instantiation we need to rotate the hosts.

    Regarding the BC static to non static, given it has only been available in 1 version and was only used internally + wasn't even called statically, I think we are safe doing the change.

    TODO:

    • [x] Unit tests
    • [x] Choose if we push the file based cache by default or if we keep the in memory strategy
    • [x] Implement in memory cache invalidation for long running PHP processes > 5min
    • [x] See what we do about the static to public method signature of addFailingHost (BC) that was only introduced in last version
    opened by rayrutjes 15
  • Refactoring, mainly docblocks and CS.

    Refactoring, mainly docblocks and CS.

    Started correcting some docblocks, and refactored some small pieces.

    Please note that I have not a deep understanding of the behaviour of this client yet, so please tell me if some changes may break something. Hope the tests will catch problems though.

    • [x] Run php-cs-fixer and add a basic .php_cs config
    • [x] Add missing return tags
    • [x] Enhance the docblocks
    • [x] Use more fine grained params and return types
    • [x] Try to refactor some pieces of code that are repeated a lot
    • [x] Better format long docblocks

    Do you guys see any interest in these adjustments if they do not introduce BC issues?

    Please react on the changes so I can adjust the PR.

    Fixes #32

    opened by rayrutjes 12
  • Proxy support

    Proxy support

    Added support for custom curl options like CURLOPT_PROXY, CURLOPT_PROXYPORT... On construct you can specified an array with curl options:

    $options = [
        'curloptions' => [
            CURLOPT_PROXY => 'tcp://1.2.3.4:80',
            CURLOPT_PROXYPORT => '8080',
            CURLOPT_PROXYUSERPWD => 'USERNAME:PASSWORD',
            //...
        ]
    ];
    
    $client = new Client(
                'app-id',
                'admin_api_key',
                null,
                $options
            );
    

    if a bad curl option is given, proper exceptions are thrown :

    • InvalidArgumentException when not an array
    • OutOfBoundsException when not a valid curl option
    opened by pactole 12
  • [2.0] Add `count` method to ObjectIterator

    [2.0] Add `count` method to ObjectIterator

    Hi

    I would like to submit a PR to add a public method to the ObjectIterator which enables getting the number of the records in the index available in the api response when the broweObjects method is called. something along these lines

    public function getNbHits() { return isset($this->response['nbHits']) ? $this->response['nbHits'] : null; }

    Would that be acceptable ?

    Thank you.

    Discussion 
    opened by borealsmith 11
  • Exception code

    Exception code

    | Q | A | ------------- | --- | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests? | yes | Doc? | no | Fixed tickets | https://github.com/algolia/algoliasearch-client-php/issues/283

    Description

    This PR catches an Exception code to distinct different type of AlgoliaException..

    opened by roukmoute 11
  • Algolia addObject method not working for floats.

    Algolia addObject method not working for floats.

    a simple add object method like this

    $index->addObject( [ "avg_rating"=> 1.23456, 'objectID' => '573' ]);

    will result in an avg_rating of 0 on my algolia online records. However when i change avg_rating to 1 or 1.0, it is stored as 1. It seems that it cannot store any decimal point numbers. I am using the codeigniter framework. Does anyone else have that issue?

    opened by luo-justin 10
  • Implement statefull connection retry strategy

    Implement statefull connection retry strategy

    Resolves: #181

    This PR will rotate the hosts array at each failed connection attempt. ClientContext holds the state and the Client simply ask for a rotation by passing the "justUnresolvable" host as argument.

    Shared state between different instances of the Client: Given the current design of the Client, sharing state between different Client instances is not feasable. Also I don't think it is a big issue because most of the time, there will only be one instance of the client per PHP thread.

    If for some reason a user wants to share the state between multiple instances of a the client, he could simply override the ClientContext on all the Client. Shared state between different PHP processes In PHP processes don't share state between them, every process spawning is an attempt to recover connection to the main host. In a future version of the API Client, we could create an abstraction around the state to share it via storage layer (ideally in memory k/v store), but for now this will be overkill and very messy to implement.

    Let me know your thoughts @maxiloc @JanPetr @redox

    opened by rayrutjes 10
  • Add some new exceptions

    Add some new exceptions

    Hi.

    I added some new exceptions to make error handling easier. We have a project where we need some specific processing depending on the error returned by the API, and it would be nice if we can have it thrown directly by the client api. :)

    (I didn't move the AlgoliaException.php to keep compatibility.)

    opened by modnarlluf 10
  • Consider adding static analysis

    Consider adding static analysis

    • Algolia Client Version: N/A
    • Language Version: N/A

    Description

    Consider using a static analysis tool (like PHPStan or Pslam), in order to catch basic errors, like the class not found issue introduced recently.

    Currently there is no way to verify that code that is not covered by tests isn't broken. With static analysis all code would be automatically type checked, which should make it (nearly) impossible for these kind of errors to happen.

    It shouldn't be too much work to set it up with real low strictness, which should catch any basic errors. At a later point it could be configured to be more strict, catching more specific errors.

    If you need any help with setting this up, i'd be more than happy to help.

    opened by BackEndTea 2
  • [RFC] Make troubleshooting stuck tasks easier

    [RFC] Make troubleshooting stuck tasks easier

    Hi! I'm working with @julienpa to get the applications of my company on a new Algolia architecture, and I'm facing issues where some of the cronjobs I have to run appear to be stuck sometimes.

    I'd like to be able to easily implement custom logic where I start logging the taskID with an increasingly high log level when exceeded an arbitrary duration, and I would like that logic to kick in whenever I call wait() on a response.

    This seems to result in this method being called: https://github.com/algolia/algoliasearch-client-php/blob/ffef644ac41411f64e4522157ed53fb825b0908a/src/SearchIndex.php#L604-L620

    It would be great if the current implementation of the retry logic could be extracted in a separate class, and if there was an interface I could implement with my custom logic and if I was able to inject my custom implementation in the configuration so that it replaces the default implementation.

    Right now, the workaround would be to extend the SearchIndex, override that method, extend SearchClient and override initIndex so that it returns the overridden SearchIndex.

    opened by greg0ire 0
  • Misleading error handling

    Misleading error handling

    • Algolia Client Version: 3.2.0
    • Language Version: 8.1.2

    Description

    It seems like the current implementation of the exception is misleading:

    https://github.com/algolia/algoliasearch-client-php/blob/ffef644ac41411f64e4522157ed53fb825b0908a/src/RetryStrategy/ApiWrapper.php#L151-L196

    To day, I got the following exception Impossible to connect, please check your Algolia Application Id.

    Turning on logging revealed that this was in fact due to a missing feature on a new infrastructure we are testing:

    ^ array:3 [
      "level" => "debug"
      "message" => "Algolia API client: Host failed."
      "context" => array:7 [
        "body" => array:1 [
          "numericFilters" => "document_update_time < 1650806228"
        ]
        "headers" => array:4 [
          "X-Algolia-Application-Id" => "redacted"
          "X-Algolia-API-Key" => "redacted"
          "User-Agent" => "Algolia for PHP (3.2.0); PHP (8.1.2); Guzzle (7)"
          "Content-Type" => "application/json"
        ]
        "method" => "POST"
        "query" => []
        "retryNumber" => 4
        "host" => "https://mlnqxjqtya-1.algolianet.com/1/indexes/int_products_gb/deleteByQuery"
        "description" => "Retriable failure on mlnqxjqtya-1.algolianet.com: Not Implemented"
      ]
    ]
    

    I would expect never to get an exception that is plain wrong. Before getting this issue, I had a problem where my index name was wrong, but it was diagnosed in the same way: Impossible to connect, please check your Algolia Application Id..

    What I would expect would be the last error to be remembered and used in the exception message. Also, the exception type is wrong: the host was not unreachable, it was missing a feature.

    opened by greg0ire 0
  • NotFoundException too general to catch

    NotFoundException too general to catch

    • Algolia Client Version: 3.2.0
    • Language Version: 7.4

    Description

    Hi there,

    I'm using the client to retrieve product recommendations based on the bought-together and related-products models. Some of our indexes don't have enough events to train models so they shouldn't be used for recommendations, but it's possible that we misconfigure this somewhere, or that the number of events drops for indexes that did have enough events at some point.

    Where there's no trained model (but the index does exist) I get the following exception:

    (stack trace limited to vendor namespace only)

    Fatal error:  Uncaught Algolia\AlgoliaSearch\Exceptions\NotFoundException: Index ai_recommend_webshop-products-se:related-products.indice.bin does not exist in ./vendor/algolia/algoliasearch-client-php/src/RetryStrategy/ApiWrapper.php:217
    Stack trace:
    #0 ./vendor/algolia/algoliasearch-client-php/src/RetryStrategy/ApiWrapper.php(167): Algolia\AlgoliaSearch\RetryStrategy\ApiWrapper->handleResponse()
    #1 ./vendor/algolia/algoliasearch-client-php/src/RetryStrategy/ApiWrapper.php(101): Algolia\AlgoliaSearch\RetryStrategy\ApiWrapper->request()
    #2 ./vendor/algolia/algoliasearch-client-php/src/RecommendClient.php(85): Algolia\AlgoliaSearch\RetryStrategy\ApiWrapper->write()
      thrown in ./vendor/algolia/algoliasearch-client-php/src/RetryStrategy/ApiWrapper.php on line 217
    
    

    I would like to catch this kind of exception, but it is identical in type to the exception I get when the index doesn't exist:

    Fatal error:  Uncaught Algolia\AlgoliaSearch\Exceptions\NotFoundException: Index does not exist in ./vendor/algolia/algoliasearch-client-php/src/RetryStrategy/ApiWrapper.php:217
    

    Ideally this would be a different kind of exception so my code can handle missing/untrained models but doesn't handle missing indexes since that's a much more grave error. Attempting to parse the exception message seems a little unreliable, as those messages might change without us noticing.

    Steps To Reproduce

    1. Request a recommendation from an existing index without a trained model.
    opened by JeroenBakker 0
  • feat: bootstrap new testing strategy

    feat: bootstrap new testing strategy

    | Q | A | ----------------- | ---------- | Bug fix? | no | New feature? | no | BC breaks? | no

    Describe your change

    This bootstraps a new way to test our API client, where (for PRs) we test the formed requests instead of calling Algolia directly.

    opened by DevinCodes 4
Releases(3.3.2)
  • 3.3.2(Sep 22, 2022)

  • 3.3.1(Aug 2, 2022)

  • 3.3.0(Jul 6, 2022)

  • 3.2.0(Jan 4, 2022)

    Added

    • Add #[\ReturnTypeWillChange] when needed for PHP 8.1 compatibility (#697)

    Changed

    • chore: move to newer CircleCI image (#688)
    • chore: add PHP 8.1 image check in the CircleCI workflow (#699)

    Fixed

    • Fix Psr log (#696)
    • Allow newer version of psr/simple-cache (#698)
    Source code(tar.gz)
    Source code(zip)
  • 3.1.0(Aug 31, 2021)

  • 3.0.2(May 4, 2021)

  • 3.0.1(Apr 23, 2021)

  • 3.0.0(Apr 14, 2021)

  • 2.8.0(Apr 7, 2021)

  • 2.7.2(Nov 24, 2020)

  • 2.0.0(Nov 22, 2018)

    Please find the upgrade guide here: https://www.algolia.com/doc/api-client/getting-started/upgrade-from-v1/php/

    Additonal information are available here: https://discourse.algolia.com/t/introducing-php-api-client-v2/5635

    Source code(tar.gz)
    Source code(zip)
  • 1.28.0(Nov 6, 2018)

    • Introduce $client->multipleGetObjects() to retrieve objects via ObjectID across multiple indices

    • fix $index->waitTask to return task, behavior prior to 1.27.0

    Source code(tar.gz)
    Source code(zip)
  • 2.0.0-RC(Nov 1, 2018)

  • 2.0.0-alpha.2(Aug 20, 2018)

    • Add getter and setter for Index::indexName property
    • Fix Travis
    • Introduce ClientConfiguration (which holds ClusterHosts)
    • Introduce Client singleton with Client::get()
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0-alpha.1(Jul 12, 2018)

    Read more on our forum: https://discourse.algolia.com/t/introducing-php-api-client-v2/5635

    Since 2.0.0-alpha

    • Add multiple indexes search/index methods
    • Add common files (licence, changelog...)
    • Rename index to initIndex for easier upgrade
    • Fix default HttpClient wrapper for PHP53
    • Setup Travis
    Source code(tar.gz)
    Source code(zip)
  • 1.27.0(Jun 19, 2018)

    • Introduce AB Testing feature - PR #408 List/Create/Stop/Delete AB Tests programmatically Introduce new Analytics object, wrapper around the Analytics API (more methods to come).

    • 2 methods about taskID initially available in the Index moved to the Client. You could get some taskID from the engine without necessarily have an instance of Index, instead of instanciating an index that you won't need, you can now call waitTask and getTaskStatus on the client. The original methods on the index still work are not deprecated.

      $client->waitTask($indexName, $taskID)
      $client->getTaskStatus($indexName, $taskID)
      
    Source code(tar.gz)
    Source code(zip)
  • 1.26.1(Jun 15, 2018)

  • 1.26.0(Jun 7, 2018)

    🎉 Note to contributors: Everybody is now able to run the test on Travis, since we moved to temporary credentials.️ ⤵️ https://blog.algolia.com/travis-encrypted-variables-external-contributions/

    • Fix: addApiKey was fixed in 1.25.0 (see changelog entry below). The same fix was ported to updateApiKey.

    • Fix: Curl was added to the composer requirements. If you get an error because curl is not enabled in CLI, enable it or use the flag --ignore-platform-reqs

    • Fix: Adding a rule with an empty ID failed silently, it will now throw an exception

    • Deprecation: Keys should not be managed at the Index level but at the Client level

      All methods Index::(list|get|add|update)ApiKeys() are now deprecated. If you already have keys on the Index, it would be best to delete them and regenerate new keys with client, adding the indexes restriction.

      Example:

      $client->addApiKey([
          'acl' => 'search',
          'indexes' => 'my_index_name',
      ])
      
    • Fix: Add $requestHeaders arg to Index::browse and Index::deleteBy

    • Fix: When browsing, ensure cursor is passed in the body Cursor can become so long that the generated URL fails (error HTTP 414).

    • Chore: Add PHP version to the UserAgent

    Source code(tar.gz)
    Source code(zip)
  • 1.25.1(Mar 2, 2018)

    1.25.1

    • feat(places): Set write hosts when using Places

    Even though Algolia Places indices are read-only, we still need to take into account the write hosts to let the user generate its own API keys.

    Source code(tar.gz)
    Source code(zip)
  • 1.25.0(Dec 28, 2017)

    • feat: Let you define all API keys capabilities in one array

    Example:

    $client->addApiKey([
        'acl' => [
            'search',
            'listIndexes',
        ],
        'validity' => $validity,
        'maxQueriesPerIPPerHour' => 1000,
        'maxHitsPerQuery' => 50,
        'indexes' => ['prefix_*'],
    ]);
    

    instead of

    $client->addApiKey(['search', 'listIndexes'], $validity, 1000, 50, ['prefix_*']);
    
    Source code(tar.gz)
    Source code(zip)
  • 1.24.0(Dec 12, 2017)

  • 1.23.1(Nov 7, 2017)

    • fix: remove all requestHeaders params from method signatures as it breaks backward compatibility. Features added in 1.23.0 still work the same.
    Source code(tar.gz)
    Source code(zip)
  • 1.23.0(Oct 26, 2017)

    • feat: add a requestHeaders parameter to every method to allow passing custom HTTP headers on a per request basis
    • feat: add multi cluster management endpoints
    Source code(tar.gz)
    Source code(zip)
  • 1.22.0(Oct 17, 2017)

  • 1.21.0(Oct 6, 2017)

    • feat: exclude disjunctive queries from analytics
    • fix: autoload Tests namespace only in dev
    • fix: remove usage of deprecated API key methods
    Source code(tar.gz)
    Source code(zip)
  • 1.20.0(Aug 31, 2017)

  • 1.19.0(Aug 28, 2017)

  • 1.18.0(May 22, 2017)

    • make API credentials optional for Client::initPlaces()
    • make API credentials optional if places enabled in ClientContext class
    • raise exception when unknown method is called on Index class
    Source code(tar.gz)
    Source code(zip)
  • 1.17.0(Apr 3, 2017)

  • 1.16.0(Feb 28, 2017)

Owner
Algolia
Open source tools for building search. Learn more at community.algolia.com
Algolia
A list of all the Belgian stations and their properties used within the iRail project

All stations in Belgium We try to maintain a list of all the stations in Belgium using CSV so everyone can help to maintain it on github. Furthermore,

null 33 Nov 16, 2022
Use middleware to decorate method calls within your application code.

Laravel Middlewarize ?? Chain of Responsibility Design Pattern In Laravel Apps ?? You can use middlewares to decorate any method calls on any object.

Iman 99 Jan 1, 2023
Easily integrate custom-made NPS (Net Promoter Score) into your application

Laravel NPS Easily integrate custom-made NPS (Net Promoter Score) to your application. Installation You can install the package via composer: composer

H-FARM Innovation 48 Oct 27, 2022
Provides tools for building modules that integrate Nosto into your e-commerce platform

php-sdk Provides tools for building modules that integrate Nosto into your e-commerce platform. Requirements The Nosto PHP SDK requires at least PHP v

Nosto 5 Dec 21, 2021
Shopware plugin to show a variant switch on the product listing and within the (checkout) cart.

Variant switch for Shopware 6 A plugin for Shopware 6 Features Show variant switch on product listing card Variant switch when hovering a variant prop

Shape & Shift 17 Aug 26, 2022
Bundle to integrate Tactician with Symfony projects

TacticianBundle Symfony2 Bundle for the Tactician library https://github.com/thephpleague/tactician/ Installation Step 1: Download the Bundle Open a c

The League of Extraordinary Packages 240 Jan 4, 2023
A simple PHP project to make API requests on your cPanel installation

A simple PHP project to make API requests on your cPanel installation. This allows you to call modules inside the installation and interact with them to add, show or list data such as domains, e-mail accounts, databases and so on.

Elias Häußler 0 Sep 15, 2022
Raidbots API wrapper which incorporates existing reports and static data into your project.

Raidbots API Raidbots API wrapper which incorporates existing reports and static data into your project. Usage use Logiek\Raidbots\Client; $client =

Logiek 2 Dec 23, 2021
The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructure and leverage the power of 1Password Secrets Automation

1Password Connect PHP SDK The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructu

Michelangelo van Dam 12 Dec 26, 2022
Monorepo of the PoP project, including: a server-side component model in PHP, a GraphQL server, a GraphQL API plugin for WordPress, and a website builder

PoP PoP is a monorepo containing several projects. The GraphQL API for WordPress plugin GraphQL API for WordPress is a forward-looking and powerful Gr

Leonardo Losoviz 265 Jan 7, 2023
PHP implementation of JSON schema. Fork of the http://jsonschemaphpv.sourceforge.net/ project

JSON Schema for PHP A PHP Implementation for validating JSON Structures against a given Schema with support for Schemas of Draft-3 or Draft-4. Feature

Justin Rainbow 3.4k Dec 26, 2022
Monorepo of the PoP project, including: a server-side component model in PHP, a GraphQL server, a GraphQL API plugin for WordPress, and a website builder

PoP PoP is a monorepo containing several projects. The GraphQL API for WordPress plugin GraphQL API for WordPress is a forward-looking and powerful Gr

Leonardo Losoviz 265 Jan 7, 2023
Symfony Health Check Bundle Monitoring Project Status

Symfony Health Check Bundle Version Build Status Code Coverage master develop Installation Step 1: Download the Bundle Open a command console, enter y

MacPaw Inc. 27 Jul 7, 2022
Check a project's code coverage, optionally enforcing a minimum value

coverage-check Display the code coverage for a project using a clover.xml file, optionally enforcing a minimum code coverage percentage. This package

Permafrost Software 15 Aug 9, 2022
Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota & International

Courier API Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota (dalam negeri) & International

Rangga Darmajati 2 Sep 24, 2021
this is a project done with laravel, I created API.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

NIKA ZEREKIDZE 1 Oct 27, 2021
My first laravel restful api project

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Amirhosein Mohammadian 2 Oct 13, 2021
Meta package tying together all the key packages of the Symfony CMF project.

This repository is no longer maintained Due to lack of interest, we had to decide to discontinue this repository. The CMF project focusses on the Rout

Symfony CMF 733 Dec 21, 2022
This project lists all the mandatory steps I recommend to build a Website using Symfony, Twig, Doctrine.

{% raw %} <-- keep this for Jekyll to fully bypass this documents, because of the Twig tags. Symfony Website Checklist ?? Summary~~~~ Elevator pitch P

William Pinaud 6 Aug 31, 2022