Skip navigation

An API file consists of functions that provide methods of communication between a module and other modules (including itself). For example to allow interaction with database tables associated with that module; instead of duplicating a basic select statement across multiple files, we could just create a function inside the API file that returns the result of that select statement.

This makes life much easier, specially when there are complex queries (like containing pagination and stuff) that need to be called from several controllers or actions. Even better, we won’t need to worry if for example a tablename has changed in an update or something, since all we will be updating is the API to match the new name.

In a module, APIs are created inside the “Api” folder. I think it’s a SE convention to name the basic/ default API for a module as “Core”. However assume we’re creating an API called “Myapi” just for the sake of learning.

Assume we’re in a module called “Mymodule”. Inside the “Api” folder create a file called “MyApi.php” that contains the following:

<?php

class Mymodule_Api_Myapi extends Core_Api_Abstract{

}

?>

Notice the naming convention of the class name: {ModuleName}_Api_{ApiName}

Now just add any function to that class so it becomes something like this

<?php

class Mymodule_Api_Myapi extends Core_Api_Abstract{

public function addNumbers($a, $b){

return $a+$b;

}

}

?>

Of course an API would contain more sophisticated functions than addition, but that is just an example. Now in order to call this function from anywhere in the application:

$myApi =  Engine_Api::_()->getApi(‘myapi’, ‘mymodule’);

$sum = $myApi->addNumbers(10, 5);

“getApi” takes API name and Module name as parameters, and returns an instance of the API.

Advertisement

3 Comments

  1. Thanks for all these tutorials, you are a lifesaver!

    Have you got any more planned?

  2. Also it’s worth noting that to access any of the built-in APIs, you use a similar format: $var = Engine_Api::_()->[module_name]->[function_name](). The [function_name]s can be found in the module’s API file listed under: application/modules/[module_name]/Api/Core.php.

    Where [module_name] can be replaced with ‘core’, ‘user’, etc.

    After doing many customizations for SE so far, following the DRY — don’t repeat yourself — principle is rather difficult. Understanding this bit helped a good amount in cutting down the amount of custom functions I’ve had to create.


One Trackback/Pingback

  1. [...] Creating an API [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 31 other followers