Client-side search API


How to enable the client-side search API?

When using Outlast Framework you may sometimes run into the cryptic called undefined method '__onSearch'! error.

This means that you are trying to use the client-side search API on a model where this feature has not yet been enabled.

Most of the time, you’ll want only admins to be able to access client-side search API. It is often required to display the options in admin interfaces. Here’s an example:

	/**
	 * Items are now restricted to admins only.
	 * @param zajFetcher $fetcher
	 * @return zajFetcher
	 */
	public static function __onSearch($fetcher){
		$user = User::fetch_by_session();
		if(!is_object($user) || $user->data->admin != 'admin') return zajLib::me()->warning("You do not have access to this API!");
		return $fetcher;
	}

It’s also very simple to enable full public access to the client-side search API for any model. This can be dangerous! See below! All you have to do is add a static __onSearch method to your model. Here’s an example:

	/**
	 * Items are now restricted to admins only.
	 * @param zajFetcher $fetcher
	 * @return zajFetcher
	 */
	public static function __onSearch($fetcher){ return $fetcher; }
// WARNING AGAIN! This will make all of your objects publicly searchable! Make sure you do want this!

The dangers of client-side search API

A completely public client-side search API means that anyone who knows the API endpoint (which is NOT a secret) can fully search all elements of that model. For something like Product objects in a shop this may not be problem, but for private objects such as User you will want to add some level of authentication or restriction as in the example above.

How to use the client-side search API

[todo: add more docs!]

Changing the returned json data

You can declare the __toSearchApiJson magic method in your model to specify what fields are returned about each result item in the search results json data. By default, the method is implemented as follows:

public function __toSearchApiJson(){
  return ['id'=>$this->id, 'name'=>$this->name];
}

…but you can change this in any number of ways (add more fields, change the name to a different value, etc.).

Outlast Web & Mobile Development (c) 2023 | Privacy Policy |