Giter Site home page Giter Site logo

algolia / algoliasearch-client-php Goto Github PK

View Code? Open in Web Editor NEW
665.0 89.0 115.0 43.27 MB

⚡️ A fully-featured and blazing-fast PHP API client to interact with Algolia.

Home Page: https://www.algolia.com/doc/api-client/php/getting-started/

License: MIT License

PHP 99.90% Dockerfile 0.10%
search-engine algolia-search php algolia faceted-search search-synonyms geo-search search api-client

algoliasearch-client-php's Introduction

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.3 and ^8.0.

💡 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->saveObject(['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.

algoliasearch-client-php's People

Contributors

ahfeel avatar algoliareadmebot avatar aseure avatar carusogabriel avatar cbaptiste avatar chloelbn avatar damcou avatar damienalexandre avatar dessaigne avatar devincodes avatar e1himself avatar freekmurze avatar greg0ire avatar ivank avatar janpetr avatar jimbojsb avatar julienbourdeau avatar marcbrillault avatar maxiloc avatar nunomaduro avatar pactole avatar pixelastic avatar rayrutjes avatar rcatlin avatar redox avatar seafoox avatar speedblue avatar tomklotzpro avatar vdechenaux avatar vinkla avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

algoliasearch-client-php's Issues

forwardToReplicas not working

I've set $forwardToReplicas to true, but the replicas don't inherit searchableAttributes or attributesForFaceting. Is there something I'm missing?

$algolia->initIndex('products')->setSettings([
    'replicas' => [
        'products_popular',
        'products_newest',
    ],
    'ranking' => [
        'desc(trend)',
        'typo',
        'words',
        'filters',
        'proximity',
        'attribute',
        'exact',
        'custom',
    ],
    'searchableAttributes' => [
        'title,slug',
        'unordered(description)',
    ],
], true);

Tuber_Size

Estimado Omar:

Los valores de tuber_size, según el manual van de 1 al 9. Quisera saber por qué cuando se han colocado valores de "0" (ceros), no se pintan las celdas....? o los valores se permiten desde cero.... ??. Adjunto una captura de pantalla. Gracias :)

image

Multi level OR / AND in security tags

Let's say I want to do this config for my security tags
(public AND (catalogue_1 OR catalogue_2)) OR plateform_1

which is in PHP
array( array('public', array('catalogue_1', 'catalogue_2')), 'plateform_1' );

Doing so leads to this error
Array to string conversion in vendor/algolia/algoliasearch-client-php/src/AlgoliaSearch/Client.php:376

Hosts unreachable

Hi am getting this host's unreachable exception

Hosts unreachable: Operation timed out after 1089 milliseconds with 0 out of 0 bytes received,Operation timed out after 1002 milliseconds with 0 out of 0 bytes received,Resolving timed out after 3000 milliseconds,Operation timed out after 3033 milliseconds with 0 out of 0 bytes received

if this an issue related to request timeout then how can I increase request timeout.

Thanks

Tag new version

Are there any plans to tag a new release version?

The recent changes will only be included for composer users when using the 'dev-master' version qualifier. Using 'dev-master' isn't recommended. We are using '1.2.*'.

Path to ca-bundle.crt is not configurable.

Would be really nice if we could over-ride the path to ca-bundle.crt. Some uses of the client might require a slightly different directory structure which, by proxy, can lead to some awkward requirements for the placement of the resources directory. Making this path configurable would be really nice.

partialUpdateObject() Deletes old values when used

I am uploading a few items into Algolia and later I update a few values using this function:

public function partialUpdateObject($partialObject, $createIfNotExists = true)
    {
        $queryString = $createIfNotExists ? '' : '?createIfNotExists=false';
        return $this->client->request(
            $this->context,
            'POST',
            '/1/indexes/'.$this->urlIndexName.'/'.urlencode($partialObject['objectID']).'/partial'.$queryString,
            array(),
            $partialObject,
            $this->context->writeHostsArray,
            $this->context->connectTimeout,
            $this->context->readTimeout
        );
    }

The first few times it works, but later when I use the update record I can se that I deletes other values in my record.
Eg:

When I first uploaded a record I had a value called thumbnail which contained a url.
When I later used the partialUpdateObject() to update a value called title the thumbnail value got removed from my record.

So how do I update certain values without removing other values? Lets say that I only want to update the title value of my record and nothing else

Query multiple indices in PHP?

Hi there, not sure this is the right place to ask this,
the PHP documentation display a Query multiple indices part but examples are written in Javascript.

It looks like the PHP client does not support this interface? (there is "batch" for writing, not for reading)

I didn't look at the JavaScript implementation yet, but either ways:

  • if this an API method, we could simply add it;
  • if this use two concurrent HTTP calls, this can be done in PHP too.

Thx,
Damien

curl_multi_exec is causing high throughput

algolia-multi-exec-throughput

Every few weeks, we see this happening on our servers. The only usage of curl_multi_exec is in the algolia SDK. Currently investigating some more on reasons why this might be happening.

We are on PHP 5.6.26

Code in question:

    $running = null;
    do {
        $mrc = curl_multi_exec($mhandle, $running);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);

    while ($running && $mrc == CURLM_OK) {
        if (curl_multi_select($mhandle, 0.1) == -1) {
            usleep(100);
        }
        do {
            $mrc = curl_multi_exec($mhandle, $running);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }

Error on the deleteByQuery method when Distinct > 1

In the case the distinct is enabled on an index (with distinct > 1), a call to the method deleteByQuery returns the following error:

{
  "message": "invalid distinct value, hitsPerPage * distinct should be <= 1000",
  "status": 400
}

We should probably override distinct=false at query time when the method performs the search call.

Check for JSON errors after json_encode() as well as json_decode()

If you attempt to send malformed UTF-8 to Algolia you get 400 Bad Request as the HTTP response, this is because json_encode() fails earlier and sends an empty string instead of the correct JSON packet.

There is already a sanity check for the returned JSON, it would be good to add a similar sanity check before attempting to send any JSON to make this situation easier to debug.

[IMPORTANT] Remove latest 1.7.1.1 release

The minor fixes release 1.7.1.1 should be deleted and retagged as 1.7.2.

Also the 1.7.1 release introduced new features and should've been tagged as 1.8.0. We shouldn't change this release since it is already tagged but we need to think of this in the future before tagging new versions of the package.

1.3.2 = MAJOR.MINOR.PATCH http://semver.org/

Ping @maxiloc @redox

Add differents AlgoliaException code

It would be nice to have differents exceptions code to treat them differently.

For example with a RabbitMQ, if we receive an host unreacheable error, we would like to send a retry exchange.

Version class perform useless file_get_contents for all requests

I think all this code in Version.php could be replaced by a simple const:

  public static function getValue() {
    if (!isset(self::$value)) {
      $vpath = dirname(__FILE__) . "/../../composer.json";
      if (file_exists($vpath)) {
        $composerJson = file_get_contents($vpath);
        if ($composerJson != false) {
          $composer = json_decode($composerJson);
          if ($composer != null) {
            self::$value = $composer->version;
            return self::$value;
          }
        }
      }
      self::$value = "N/A";
    } else {
      return self::$value;
    }
  }

Because:

  • you do not need a "version" key in the composer.json file, you already use git tags and composer/packagist read them;
  • this will perform disk access each time we use the client, which is bad for performances;
  • a PHP constant will be better for users not using Composer;

All you have to do is to update the const when you tag a new version instead of updating the composer file.

So, new Version.php:

namespace AlgoliaSearch;

class Version {
    const NUMBER = '1.5.2';
}

I can send the pull request if you agree with my statements.

Fix brittle tests

It looks like some tests occasionally fails due to data not being available yet on Algolia's side.

1) AlgoliaSearch\Tests\BasicTest::testMultipleQueries
AlgoliaSearch\AlgoliaException: Index àlgol?à-php_travis-5 does not exist
/home/travis/build/algolia/algoliasearch-client-php/src/AlgoliaSearch/Client.php:928
/home/travis/build/algolia/algoliasearch-client-php/src/AlgoliaSearch/Client.php:745
/home/travis/build/algolia/algoliasearch-client-php/src/AlgoliaSearch/Client.php:263
/home/travis/build/algolia/algoliasearch-client-php/tests/AlgoliaSearch/Tests/BasicTest.php:141
2) AlgoliaSearch\Tests\SearchFacetTest::testSearchTest
AlgoliaSearch\AlgoliaException: Cannot search in `series` attribute, you need to add `searchable(series)` to attributeForFaceting.
/home/travis/build/algolia/algoliasearch-client-php/src/AlgoliaSearch/Client.php:928
/home/travis/build/algolia/algoliasearch-client-php/src/AlgoliaSearch/Client.php:745
/home/travis/build/algolia/algoliasearch-client-php/src/AlgoliaSearch/Index.php:533
/home/travis/build/algolia/algoliasearch-client-php/tests/AlgoliaSearch/Tests/SearchFacetTest.php:83

Optimize re-try strategy by updating last working DN in the context

Currently, we will always try to connect to the same, eventually non reachable, DN before moving to the next one.

When a domain is not reachable, we should reflect it in the ClientContext so that we don't introduce a delay of the amount of the timeout for every call to the API for the same process.

Composer doesn't find the package

Hi, I had to add this to my composer.json to install the library:

"repositories": [
        {
            "type": "git",
            "url": "https://github.com/algolia/algoliasearch-client-php"
        }  
],

You should probably either update the docs or publish the library to https://packagist.org/

Search with facets Disjunctive & Conjunctive at the same time

I haven't found a way to make a search which contains some disjunctive facets and some conjunctive facets, using searchDisjunctiveFacets.
Is it possible to do that?

There is a way to make an OR between facets by using filters, but is it going to retrieve the values for the facets that are not passed?

Hosts unreachable: SSL certificate problem: Couldn't understand the server certificate format

Hello,

I'm trying to make a search with laravel using the sample code

$results = $this->model->search($searchQuery)->get();

But I get the error

AlgoliaException in Client.php line 752:
Hosts unreachable: SSL certificate problem: Couldn't understand the server certificate format,SSL certificate problem: Couldn't understand the server certificate format,SSL certificate problem: Couldn't understand the server certificate format,SSL certificate problem: Couldn't understand the server certificate format

My Environment

PHP Version: PHP 7.1.1
Operating System: OS X 10.12.6
cURL Version: 7.54.0

Certificate Read

I was getting a CURL error saying curl couldn't find the cert. It has something to do with how you require files. I changed this to help.

curl_setopt($this->curlHandle, CURLOPT_CAINFO, './resources/ca-bundle.crt');

to

curl_setopt($this->curlHandle, CURLOPT_CAINFO, DIR . '/resources/ca-bundle.crt');

DIR = "underscore underscore DIR underscore underscore"
Github won't let me write it.

P.S. This is for PHP 5.3+

Mock API calls

There seem to be no way to mock Algolia's API call in the php client. What do you suggest?

File existance check for Version class

Please add check for existance before trying to get value (line 34) to prevent "failed to open stream: No such file or directory" warning in some cases.
Maybe simply something like this:

    $vpath = dirname( __FILE__ ) . "/../../composer.json";
    if ( file_exists($vpath) ) {

        $composerJson = file_get_contents( $vpath );
        if ( $composerJson != FALSE ) {
            $composer = json_decode( $composerJson );
            if ( $composer != NULL ) {
                self::$value = $composer->version;

                return self::$value;
            }
        }
    }

PHP Client performs poorly

According to my profiling result, in case of JS client it is reported that the wall-clock time is 3 ms. But with the PHP client it takes 300 ~ 400 ms.

In your Client::doRequest method, 7~50 loop happens while requesting CURL. Any plan to replace CURL to another http client? I'll do my test with Algolia REST API and guzzle today.

The following is the code that I used for profiling.
(3 consecutive queris. Don't ask why? That's just the company's requirement.)

<?php

define('ALGOLIA_START', microtime(true));

require __DIR__ . '/./vendor/autoload.php';

$client = new \AlgoliaSearch\Client('***', '***');
$storeIndex = $client->initIndex('stores_tentative');
$productIndex = $client->initIndex('products_tentative');

if (isset($_GET['q'])) {
    $keyword = $_GET['q'];

    $sections[] = $storeIndex->search($keyword, [
        'hitsPerPage' => 20,
        'filters' => 'isCvs=0 AND deliverableRegions=2906'
    ])['hits'];

    $sections[] = $productIndex->search($keyword, [
        'hitsPerPage' => 20,
        'filters' => 'isCvs=0 AND deliverableRegions=2906'
    ])['hits'];

    $sections[] = $productIndex->search($keyword, [
        'hitsPerPage' => 50,
        'filters' => 'isCvs=1 AND deliverableRegions=2906'
    ])['hits'];

    $processingTime = round((microtime(true) - ALGOLIA_START) * 1000); // 300~400 ms
}
<script>
  new Vue({
    el: '#app',

    data: {
      keyword: '',
      processingTime: 0,
      results: {
        cuisine: {
          stores: [],
          products: []
        },
        cvs: {
          stores: [],
          products: []
        }
      }
    },

    mounted: function () {
      var client = algoliasearch('***', '***');
      this.storeIndex = client.initIndex('stores_tentative');
      this.productIndex = client.initIndex('products_tentative');
    },

    methods: {
      search: function () {
        var ALGOLIA_START = performance.now();

        // Cuisine Store
        this.storeIndex.search(this.keyword, {
          filters: 'isCvs=0 AND deliverableRegions=2906',
          hitsPerPage: 20
        }, function (err, content) {
          this.results.cuisine.stores = content.hits;
        }.bind(this));

        // Cuisine Product
        this.productIndex.search(this.keyword, {
          filters: 'isCvs=0 AND deliverableRegions=2906',
          hitsPerPage: 20
        }, function (err, content) {
          this.results.cuisine.products = content.hits;
        }.bind(this));

        // CVS Product
        this.productIndex.search(this.keyword, {
          filters: 'isCvs=1 AND deliverableRegions=2906',
          hitsPerPage: 50
        }, function (err, content) {
          this.results.cvs.products = content.hits;
        }.bind(this));

        this.processingTime = Math.round(performance.now() - ALGOLIA_START); // 3 ms
      }
    }
  });
</script>

\AlgoliaSearch\Index::__call should throw an exception on unhandled methods

We just had to track down a silent failure bug where we were calling an invalid method on an index object, but not seeing any errors. This is because the __call implementation simply returns NULL if the method name is not recognised; only browse is actually handled by this method.

It would be good if an exception was thrown here to avoid others running into the same problem.

Invalid object attributes: optionalwords

I'm getting this error when I try to create a request to save an object. I didn't have this error before, it has started around 10 days. Is something I'm doing wrong or is a known bug?
Thanks!

Issue with adding a param and json error

I've described the issue over on stackoverflow with some pics.

Basically when I add a new param it causes some requests to fail with the error in that post. If I remove getRankingInfo or numericFilters from the params it works.

Any ideas? I'm unsure if it's the library, the data or Algolia. I'm guessing it's in the library code where the search call is handled and the results decoded.

[Improvements] Tag @return is missing in PhpDoc blocks

All functions are well documented for input parameters, thanks to the @param tag , but the @return tag is never used to document the return type.

This information is very useful for some IDE (like PhpStorm) that are able to warn the user about potential issues. In this case, since no return type is documented, we obtain this kind of warning messages:

'void' method 'browse' result used less... (Ctrl+F1) 
The value of a void function is most likely used by mistake, because such functions do not have a return value.

Would be nice to add these tags :)

Thanks for your work!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.