close
Phork Manual Table of Contents
Phork Framework User Guide 1.3.4

CoreApi

Filepath: phork/php/core/CoreApi.class.php
Version: 1.3.2 and higher

The CoreApi class is the base class for all API classes. It works nearly the same as a controller however it returns the results in an array instead of outputting them. This allows for the results to then be displayed by the ApiController (phork/sites/standard/controllers/ApiController.class.php) or for the methods to be called internally without having to translate the results to and from JSON or XML.

The CoreApi is set up so that it can be instantiated directly and will then delegate to the extensions based on the URL. If the API methods need calling internally without the additional HTTP request overhead this is possible by temporarily faking the URL data.


Internal Example

class ApiHelper {
    static public function get($strUrl) {
        
        //back up the current GET vars and set up any new ones
        if ($strQueryString = substr(strstr($strUrl, '?'), 1)) {
            $arrGetBackup = $_GET;
            parse_str($strQueryString, $_GET);
        }
        
        //set up the URL object to contain the URL of the API call
        $objUrl = AppRegistry::get('Url');
        $objUrl->setUrl($strUrl);
        $objUrl->init();
        
        //determine if the user is logged in
        if ($objUserLogin = AppRegistry::get('UserLogin', false)) {
            $blnAuthenticated = $objUserLogin->isLoggedIn();
        }
        
        //count the number of errors
        $objError = AppRegistry::get('Error');
        $intStartErrors = count($objError->getErrors());
        
        //initialize and run the API method
        AppLoader::includeClass('php/core/', 'CoreApi');
        $objApi = new CoreApi(!empty($blnAuthenticated), true);
        list(
            $blnSuccess, 
            $arrResult, 
            $intStatusCode
        ) = $objApi->run();
        
        //if there were major errors but nothing added to the error log add a generic error
        $intEndErrors = count($objError->getErrors());
        if ($intStatusCode >= 400 && $intEndErrors < $intStartErrors) {
            trigger_error(AppLanguage::translate('There was a fatal error'));
        }
        
        //reset the URL to the current URL
        $objUrl->setUrl(null);
        $objUrl->init();
        
        //restore the GET vars if they were overwritten
        if (isset($arrGetBackup)) {
            $_GET = $arrGetBackup;
        }
        
        return array($blnSuccess, $arrResult);
    }
}