AkObject | --AkActionController
Located in File: /AkActionController.php
$asset_host = AK_ASSET_HOST (line 53)
This makes it possible to easily move javascripts, stylesheets, and images to a dedicated asset server away from the main web server. Example: $this->_asset_host = 'http://assets.example.com';
$default_send_file_options = array(
$flash = array() (line 2076)
to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create action that sets <tt>flash['notice] = 'Successfully created'</tt> before redirecting to a display action that can then expose the flash to its template. Actually, that exposure is automatically done. Example:
class WeblogController extends ActionController { function create() { // save post $this->flash['notice] = 'Successfully created post'; $this->redirectTo(array('action'=>'display','params' => array('id' =>$Post->id))); }
function display() { // doesn't need to assign the flash notice to the template, that's done automatically } }
display.tpl <?php if($flash['notice']) : ?><div class='notice'><?php echo $flash['notice'] ?></div><?php endif; ?>
This example just places a string in the flash, but you can put any object in there. And of course, you can put as many as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
==flash_now
Sets a flash that will not be available to the next action, only to the current.
$this->flash_now['message] = 'Hello current action';
This method enables you to use the flash as a central messaging system in your app. When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>). When you need to pass an object to the current action, you use <tt>now</tt>, and your object will vanish when the current action is done.
Entries set via <tt>flash_now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
$params = array() (line 79)
Accessed like <tt>$this->params['post_id'];</tt> to get the post_id.
$Request (line 72)
$Response (line 88)
Can also be used to access the final body HTML after a template has been rendered through $this->Response->body -- useful for <tt>after_filter</tt>s that wants to manipulate the output, such as a OutputCompressionFilter.
$session (line 95)
$TemplateClass (line 61)
$_action_name (line 113)
$_assigns = array() (line 108)
$_headers = array() (line 101)
$_ignore_missing_templates (line 67)
$_includedActions = array() (line 1683)
Filters have access to the request, response, and all the instance variables set by other filters in the chain or by the action (in the case of after filters). Additionally, it's possible for a pre-processing <tt>beforeFilter</tt> to halt the processing before the intended action is processed by returning false or performing a redirect or render. This is especially useful for filters like authentication where you're not interested in allowing the action to be performed if the proper credentials are not in order.
== Filter inheritance
Controller inheritance hierarchies share filters downwards, but subclasses can also add new filters without affecting the superclass. For example:
class BankController extends AkActionController { function __construct() { $this->beforeFilter('_audit'); }
function _audit(&$controller) { // record the action and parameters in an audit log } }
class VaultController extends BankController { function __construct() { $this->beforeFilter('_verifyCredentials'); }
function _verifyCredentials(&$controller) { // make sure the user is allowed into the vault } }
Now any actions performed on the BankController will have the audit method called before. On the VaultController, first the audit method is called, then the _verifyCredentials method. If the _audit method returns false, then _verifyCredentials and the intended action are never called.
== Filter types
A filter can take one of three forms: method reference, external class, or inline method. The first is the most common and works by referencing a method somewhere in the inheritance hierarchy of the controller by use of a method name. In the bank example above, both BankController and VaultController use this form.
Using an external class makes for more easily reused generic filters, such as output compression. External filter classes are implemented by having a static +filter+ method on any class and then passing this class to the filter method. Example:
class OutputCompressionFilter { function filter(&$controller) { $controller->response->body = compress($controller->response->body); } }
class NewspaperController extends AkActionController { function __construct() { $this->afterFilter(new OutputCompressionFilter()); } }
The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can manipulate them as it sees fit.
== Filter chain ordering
Using <tt>beforeFilter</tt> and <tt>afterFilter</tt> appends the specified filters to the existing chain. That's usually just fine, but some times you care more about the order in which the filters are executed. When that's the case, you can use <tt>prependBeforeFilter</tt> and <tt>prependAfterFilter</tt>. Filters added by these methods will be put at the beginning of their respective chain and executed before the rest. For example:
class ShoppingController extends AkActionController { function __construct() { $this->beforeFilter('verifyOpenShop'); } }
class CheckoutController extends AkActionController { function __construct() { $this->prependBeforeFilter('ensureItemsInCart', 'ensureItemsInStock'); } }
The filter chain for the CheckoutController is now <tt>ensureItemsInCart, ensureItemsInStock,</tt> <tt>verifyOpenShop</tt>. So if either of the ensure filters return false, we'll never get around to see if the shop is open or not.
You may pass multiple filter arguments of each type.
== Around filters
In addition to the individual before and after filters, it's also possible to specify that a single object should handle both the before and after call. That's especially useful when you need to keep state active between the before and after, such as the example of a benchmark filter below:
class WeblogController extends AkActionController { function __construct() { $this->aroundFilter(new BenchmarkingFilter()); }
// Before this action is performed, BenchmarkingFilter->before($controller) is executed function index() { } // After this action has been performed, BenchmarkingFilter->after($controller) is executed }
class BenchmarkingFilter { function before(&$controller) { start_timer(); }
function after(&$controller) { stop_timer(); report_result(); } }
== Filter chain skipping
Some times its convenient to specify a filter chain in a superclass that'll hold true for the majority of the subclasses, but not necessarily all of them. The subclasses that behave in exception can then specify which filters they would like to be relieved of. Examples
class ApplicationController extends AkActionController { function __construct() { $this->beforeFilter('authenticate'); } }
class WeblogController extends ApplicationController { // will run the authenticate filter }
class SignupController extends AkActionController { function __construct() { $this->skipBeforeFilter('authenticate'); } // will not run the authenticate filter }
== Filter conditions
Filters can be limited to run for only specific actions. This can be expressed either by listing the actions to exclude or the actions to include when executing the filter. Available conditions are +only+ or +except+, both of which accept an arbitrary number of method references. For example:
class Journal extends AkActionController { function __construct() { // only require authentication if the current action is edit or delete $this->beforeFilter(array('_authorize'=>array('only'=>array('edit','delete'))); }
function _authorize(&$controller) { // redirect to login unless authenticated } }
$_pagination_default_options = array(
$_pagination_options = array(Active Record objects. It offers macro-style automatic fetching of your model for multiple views, or explicit fetching for single actions. And if the magic isn't flexible enough for your needs, you can create your own paginators with a minimal amount of code.
The Pagination module can handle as much or as little as you wish. In the controller, have it automatically query your model for pagination; or, if you prefer, create Paginator objects yourself
Pagination is included automatically for all controllers.
For help rendering pagination links, see Helpers/PaginationHelper.
==== Automatic pagination for every action in a controller
class PersonController extends ApplicationController { var $model = 'person'; var $paginate = array('people'=>array('order' => 'last_name, first_name', 'per_page' => 20)); }
Each action in this controller now has access to a <tt>$this->people</tt> instance variable, which is an ordered collection of model objects for the current page (at most 20, sorted by last name and first name), and a <tt>$this->person_pages</tt> Paginator instance. The current page is determined by the <tt>$params['page']</tt> variable.
==== Pagination for a single action
function show_all() { list($this->person_pages, $this->people) = $this->paginate('people', array('order' => 'last_name, first_name')); }
Like the previous example, but explicitly creates <tt>$this->person_pages</tt> and <tt>$this->people</tt> for a single action, and uses the default of 10 items per page.
==== Custom/"classic" pagination
function list() { $this->person_pages = new AkPaginator(&$this, $Person->count(), 10, $params['page']); $this->people = $this->Person->find('all', array( 'order'=> 'last_name, first_name', 'limit' => $this->person_pages->items_per_page, 'offset' => $this->person_pages->getOffset())); }
Explicitly creates the paginator from the previous example and uses AkPaginator::toSql to retrieve <tt>$this->people</tt> from the model.
$_view_controller_internals = true (line 39)
By default, it does.
Method accountHost (line 2439)
Method accountUrl (line 2432)
Method addPluginHelper (line 344)
Method addToUrl (line 1012)
Method afterAction (line 1985)
If any of the filters return false, no more filters will be executed.
Method afterFilter (line 1755)
Method afterFilters (line 1876)
Method appendAfterFilter (line 1727)
Method appendAroundFilter (line 1773)
B::before() A::before() A::after() B::after()
Method appendBeforeFilter (line 1688)
Method aroundFilter (line 1812)
Method beforeAction (line 1975)
If any of the filters return false, no more filters will be executed and the action is aborted.
Method beforeFilter (line 1715)
Method beforeFilters (line 1868)
Method buildQueryString (line 1176)
Method defaultAccountSubdomain (line 2425)
The methods are: getAccountUrl, getAccountHost, and getAccountDomain.
Example:
include_once('AkAccountLocation.php');
class ApplicationController extends AkActionController { var $before_filter = '_findAccount';
function _findAccount() { $this->account = Account::find(array('conditions'=>array('username = ?', $this->account_domain))); }
class AccountController extends ApplicationController { function new_account() { $this->new_account = Account::create($this->params['new_account']); $this->redirectTo(array('host' => $this->accountHost($this->new_account->username), 'controller' => 'weblog')); }
function authenticate() { $this->session[$this->account_domain] = 'authenticated'; $this->redirectTo(array('controller => 'weblog')); }
function _isAuthenticated() { return !empty($this->session['account_domain']) ? $this->session['account_domain'] == 'authenticated' : false; } }
// The view: Your domain: {account_url?}
By default, all the methods will query for $this->account->username as the account key, but you can specialize that by overwriting defaultAccountSubdomain. You can of course also pass it in as the first argument to all the methods.
Method defaultUrlOptions (line 920)
The default options should come in the form of a an array, just like the one you would use for $this->UrlFor directly. Example:
function defaultUrlOptions($options) { return array('project' => ($this->Project->isActive() ? $this->Project->url_name : 'unknown')); }
As you can infer from the example, this is mostly useful for situations where you want to centralize dynamic decisions about the urls as they stem from the business domain. Please note that any individual $this->UrlFor call can always override the defaults set by this method.
Method eraseRenderResults (line 709)
Method excludedActions (line 1892)
Method getActiveLayout (line 1388)
Method getDefaultTemplateName (line 1084)
Method handleRequest (line 136)
Method includedActions (line 1884)
Method instantiateHelpers (line 230)
Per example, if a helper TextHelper is located into the file text_helper.php. An instance is created on current controller at $this->text_helper. This instance is also available on the view by calling $text_helper.
Helpers can be found at lib/AkActionView/helpers (this might change in a future)
Method instantiateIncludedModelClasses (line 386)
Method instantiateModelClass (line 401)
Method paginate (line 2258)
+options+ are: <tt>singular_name</tt>:: the singular name to use, if it can't be inferred by singularizing the collection name <tt>class_name</tt>:: the class name to use, if it can't be inferred by camelizing the singular name <tt>per_page</tt>:: the maximum number of items to include in a single page. Defaults to 10 <tt>conditions</tt>:: optional conditions passed to Model::find('all', $this->params); and Model::count() <tt>order</tt>:: optional order parameter passed to Model::find('all', $this->params); <tt>order_by</tt>:: (deprecated, used :order) optional order parameter passed to Model::find('all', $this->params) <tt>joins</tt>:: optional joins parameter passed to Model::find('all', $this->params) and Model::count() <tt>join</tt>:: (deprecated, used :joins or :include) optional join parameter passed to Model::find('all', $this->params) and Model::count() <tt>include</tt>:: optional eager loading parameter passed to Model::find('all', $this->params) and Model::count()
Creates a +before_filter+ which automatically paginates an Active Record model for all actions in a controller (or certain actions if specified with the <tt>actions</tt> option).
+options+ are the same as PaginationHelper::paginate, with the addition of: <tt>actions</tt>:: an array of actions for which the pagination is active. Defaults to +null+ (i.e., every action)
Method performActionWithFilters (line 1955)
Method performActionWithoutFilters (line 1948)
Method prependAfterFilter (line 1742)
Method prependAroundFilter (line 1796)
A::before() B::before() B::after() A::after()
Method prependBeforeFilter (line 1702)
Method process (line 145)
Method redirectTo (line 781)
* <tt>Array</tt>: The URL will be generated by calling $this->UrlFor with the +options+. * <tt>String starting with protocol:// (like http://)</tt>: Is passed straight through as the target for redirection. * <tt>String not containing a protocol</tt>: The current protocol and host is prepended to the string. * <tt>back</tt>: Back to the page that issued the Request-> Useful for forms that are triggered from multiple places. Short-hand for redirectTo(Request->env["HTTP_REFERER"])
Examples: redirectTo(array('action' => 'show', 'id' => 5)); redirectTo('http://www.akelos.com'); redirectTo('/images/screenshot.jpg'); redirectTo('back');
The redirection happens as a "302 Moved" header.
Method redirectToAction (line 810)
Method render (line 569)
=== Rendering an action
Action rendering is the most common form and the type used automatically by Action Controller when nothing else is specified. By default, actions are rendered within the current layout (if one exists).
* Renders the template for the action "goal" within the current controller
$this->render(array('action'=>'goal'));
* Renders the template for the action "short_goal" within the current controller, but without the current active layout
$this->render(array('action'=>'short_goal','layout'=>false));
* Renders the template for the action "long_goal" within the current controller, but with a custom layout
$this->render(array('action'=>'long_goal','layout'=>'spectacular'));
=== Rendering partials
Partial rendering is most commonly used together with Ajax calls that only update one or a few elements on a page without reloading. Rendering of partials from the controller makes it possible to use the same partial template in both the full-page rendering (by calling it from within the template) and when sub-page updates happen (from the controller action responding to Ajax calls). By default, the current layout is not used.
* Renders the partial located at app/views/controller/_win.tpl
$this->render(array('partial'=>'win'));
* Renders the partial with a status code of 500 (internal error)
$this->render(array('partial'=>'broken','status'=>500));
* Renders the same partial but also makes a local variable available to it
$this->render(array('partial' => 'win', 'locals' => array('name'=>'david')));
* Renders a collection of the same partial by making each element of $wins available through the local variable "win" as it builds the complete Response
$this->render(array('partial'=>'win','collection'=>$wins));
* Renders the same collection of partials, but also renders the win_divider partial in between each win partial.
$this->render(array('partial'=>'win','collection'=>$wins,'spacer_template'=>'win_divider'));
=== Rendering a template
Template rendering works just like action rendering except that it takes a path relative to the template root. The current layout is automatically applied.
* Renders the template located in app/views/weblog/show.tpl $this->render(array('template'=>'weblog/show'));
=== Rendering a file
File rendering works just like action rendering except that it takes a filesystem path. By default, the path is assumed to be absolute, and the current layout is not applied.
* Renders the template located at the absolute filesystem path $this->render(array('file'=>'/path/to/some/template.tpl')); $this->render(array('file'=>'c:/path/to/some/template.tpl'));
* Renders a template within the current layout, and with a 404 status code $this->render(array('file' => '/path/to/some/template.tpl', 'layout' => true, 'status' => 404)); $this->render(array('file' => 'c:/path/to/some/template.tpl', 'layout' => true, 'status' => 404));
* Renders a template relative to the template root and chooses the proper file extension $this->render(array('file' => 'some/template', 'use_full_path' => true));
=== Rendering text
Rendering of text is usually used for tests or for rendering prepared content, such as a cache. By default, text rendering is not done within the active layout.
* Renders the clear text "hello world" with status code 200 $this->render(array('text' => 'hello world!'));
* Renders the clear text "Explosion!" with status code 500 $this->render(array('text' => "Explosion!", 'status' => 500 ));
* Renders the clear text "Hi there!" within the current active layout (if one exists) $this->render(array('text' => "Explosion!", 'layout' => true));
* Renders the clear text "Hi there!" within the layout * placed in "app/views/layouts/special.tpl" $this->render(array('text' => "Explosion!", 'layout => "special"));
=== Rendering an inline template
Rendering of an inline template works as a cross between text and action rendering where the source for the template is supplied inline, like text, but its evaled by PHP, like action. By default, PHP is used for rendering and the current layout is not used.
* Renders "hello, hello, hello, again" $this->render(array('inline' => "<?php echo str_repeat('hello, ', 3).'again'?>" ));
* Renders "hello david" $this->render(array('inline' => "<?php echo 'hello ' . $name ?>", 'locals' => array('name' => 'david')));
=== Rendering nothing
Rendering nothing is often convenient in combination with Ajax calls that perform their effect client-side or when you just want to communicate a status code. Due to a bug in Safari, nothing actually means a single space.
* Renders an empty Response with status code 200 $this->render(array('nothing' => true));
* Renders an empty Response with status code 401 (access denied) $this->render(array('nothing' => true, 'status' => 401));
Method renderAction (line 626)
Method renderFile (line 636)
Method renderPartial (line 669)
Method renderPartialCollection (line 680)
Method renderTemplate (line 649)
Method renderText (line 656)
Method renderToString (line 617)
Method renderWithALayout (line 1409)
Method renderWithLayout (line 694)
Method renderWithoutLayout (line 700)
Method rewriteOptions (line 819)
Method sendData (line 2565)
Options: * <tt>filename</tt> - Suggests a filename for the browser to use. * <tt>type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded. Valid values are 'inline' and 'attachment' (default).
Generic data download: sendData($buffer)
Download a dynamically-generated tarball: sendData(Ak::compress('dir','tgz'), array('filename' => 'dir.tgz'));
Display an image Active Record in the browser: sendData($image_data, array('type' =>Ak::mime_content_type('image_name.png'), 'disposition' => 'inline'));
See +sendFile+ for more information on HTTP Content-* headers and caching.
Method sendDataAsStream (line 2577)
This way you might free memory usage is file is too large
Method sendFile (line 2521)
Be careful to sanitize the path parameter if it coming from a web page. sendFile($params['path']) allows a malicious user to download any file on your server.
Options: * <tt>filename</tt> - suggests a filename for the browser to use. Defaults to realpath($path). * <tt>type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded. Valid values are 'inline' and 'attachment' (default). * <tt>stream</tt> - whether to send the file to the user agent as it is read (true) or to read the entire file before sending (false). Defaults to true. * <tt>buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file. Defaults to 4096.
The default Content-Type and Content-Disposition headers are set to download arbitrary binary files in as many browsers as possible. IE versions 4, 5, 5.5, and 6 are all known to have a variety of quirks (especially when downloading over SSL).
Simple download: sendFile('/path/to.zip');
Show a JPEG in browser: sendFile('/path/to.jpeg', array('type' => 'image/jpeg', 'disposition' => 'inline'));
Read about the other Content-* HTTP headers if you'd like to provide the user with more information (such as Content-Description). http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
Also be aware that the document may be cached by proxies and browsers. The Pragma and Cache-Control headers declare how the file may be cached by intermediaries. They default to require clients to validate with the server before releasing cached responses. See http://www.mnot.net/cache_docs/ for an overview of web caching and http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 for the Cache-Control header spec.
Method setDefaultTemplateName (line 1089)
Method setLayout (line 1364)
Method setModel (line 376)
Method setSslAllowedActions (line 2338)
Method setSslRequiredActions (line 2331)
Method skipAfterFilter (line 1834)
Method skipBeforeFilter (line 1823)
This is especially useful for managing the chain in inheritance hierarchies where only one out of many sub-controllers need a different hierarchy.
Method t (line 750)
Method toString (line 1102)
Overrides : AkObject::toString() Object-to-string conversion
Method urlFor (line 1007)
(For doing a complete redirect, use redirectTo).
<tt>$this->UrlFor</tt> is used to:
All keys given to $this->UrlFor are forwarded to the Route module, save for the following: * <tt>anchor</tt> -- specifies the anchor name to be appended to the path. For example, <tt>$this->UrlFor(array('controller' => 'posts', 'action' => 'show', 'id' => 10, 'anchor' => 'comments'</tt> will produce "/posts/show/10#comments". * <tt>only_path</tt> -- if true, returns the absolute URL (omitting the protocol, host name, and port) * <tt>trailing_slash</tt> -- if true, adds a trailing slash, as in "/archive/2005/". Note that this is currently not recommended since it breaks caching. * <tt>host</tt> -- overrides the default (current) host if provided * <tt>protocol</tt> -- overrides the default (current) protocol if provided
The URL is generated from the remaining keys in the array. A URL contains two key parts: the <base> and a query string. Routes composes a query string as the key/value pairs not included in the <base>.
The default Routes setup supports a typical Akelos Framework path of "controller/action/id" where action and id are optional, with action defaulting to 'index' when not given. Here are some typical $this->UrlFor statements and their corresponding URLs:
$this->UrlFor(array('controller'=>'posts','action'=>'recent')); // 'proto://host.com/posts/recent' $this->UrlFor(array('controller'=>'posts','action'=>'index')); // 'proto://host.com/posts' $this->UrlFor(array('controller'=>'posts','action'=>'show','id'=>10)); // 'proto://host.com/posts/show/10'
When generating a new URL, missing values may be filled in from the current Request's parameters. For example, <tt>$this->UrlFor(array('action'=>'some_action'));</tt> will retain the current controller, as expected. This behavior extends to other parameters, including <tt>controller</tt>, <tt>id</tt>, and any other parameters that are placed into a Route's path.
The URL helpers such as <tt>$this->UrlFor</tt> have a limited form of memory: when generating a new URL, they can look for missing values in the current Request's parameters. Routes attempts to guess when a value should and should not be taken from the defaults. There are a few simple rules on how this is performed:
* If the controller name begins with a slash, no defaults are used: <tt>$this->UrlFor(array('controller'=>'/home'));</tt> * If the controller changes, the action will default to index unless provided
The final rule is applied while the URL is being generated and is best illustrated by an example. Let us consider the route given by <tt>map->connect('people/:last/:first/:action', array('action' => 'bio', 'controller' => 'people'))</tt>.
Suppose that the current URL is "people/hh/david/contacts". Let's consider a few different cases of URLs which are generated from this page.
* <tt>$this->UrlFor(array('action'=>'bio'));</tt> -- During the generation of this URL, default values will be used for the first and last components, and the action shall change. The generated URL will be, "people/hh/david/bio". * <tt>$this->UrlFor(array('first'=>'davids-little-brother'));</tt> This generates the URL 'people/hh/davids-little-brother' -- note that this URL leaves out the assumed action of 'bio'.
However, you might ask why the action from the current Request, 'contacts', isn't carried over into the new URL. The answer has to do with the order in which the parameters appear in the generated path. In a nutshell, since the value that appears in the slot for <tt>first</tt> is not equal to default value for <tt>first</tt> we stop using defaults. On it's own, this rule can account for much of the typical Akelos Framework URL behavior.
Although a convienence, defaults can occasionaly get in your way. In some cases a default persists longer than desired. The default may be cleared by adding <tt>'name' => null</tt> to <tt>$this->UrlFor</tt>'s options. This is often required when writing form helpers, since the defaults in play may vary greatly depending upon where the helper is used from. The following line will redirect to PostController's default action, regardless of the page it is displayed on:
$this->UrlFor(array('controller' => 'posts', 'action' => null));
If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the overwrite_params options. Say for your posts you have different views for showing and printing them. Then, in the show view, you get the URL for the print view like this
$this->UrlFor(array('overwrite_params' => array('action' => 'print')));
This takes the current URL as is and only exchanges the action. In contrast, <tt>$this->UrlFor(array('action'=>'print'));</tt> would have slashed-off the path components after the changed action.
Method _actionIsExempted (line 2018)
Method _addActionConditions (line 1925)
Method _addLayoutConditions (line 1375)
Method _appendFilterToChain (line 1898)
Method _assertExistanceOfTemplateFile (line 1071)
Method _authenticate (line 2744)
If an array is given, it will check the key for a user and the value will be verified to match given password.
You can pass and array like array('handler' => $Account, 'method' => 'verifyCredentials'), which will call
$Account->verifyCredentials($user_name, $password, $Controller)
You can also pass an object which implements an "authenticate" method. when calling
$this->_authenticate(new User());
It will call the $User->authenticate($user_name, $password, $Controller)
In both cases the authentication method should return true for valid credentials or false is invalid.
Method _authenticateOrRequestWithHttpBasic (line 2707)
class PostsController extends ApplicationController { var $_authorized_users = array('bermi' => 'secret');
function __construct(){ $this->beforeFilter(array('authenticate' => array('except' => array('index')))); }
function index() { $this->renderText("Everyone can see me!"); }
function edit(){ $this->renderText("I'm only accessible if you know the password"); }
function authenticate(){ return $this->_authenticateOrRequestWithHttpBasic('App name', $this->_authorized_users); } }
Here is a more advanced Basic example where only Atom feeds and the XML API is protected by HTTP authentication, the regular HTML interface is protected by a session approach:
class ApplicationController extends AkActionController { var $models = 'account';
function __construct() { $this->beforeFilter(array('_setAccount', 'authenticate')); }
function _setAccount() { $this->Account = $this->account->findFirstBy('url_name', array_pop($this->Request->getSubdomains())); }
function authenticate() { if($this->Request->isFormat('XML', 'ATOM')){ if($User = $this->_authenticateWithHttpBasic($Account)){ $this->CurrentUser = $User; }else{ $this->_requestHttpBasicAuthentication(); } }else{ if($this->isSessionAuthenticated()){ $this->CurrentUser = $Account->user->find($_SESSION['authenticated']['user_id']); }else{ $this->redirectTo(array('controller'=>'login')); return false; } } } }
On shared hosts, Apache sometimes doesn't pass authentication headers to FCGI instances. If your environment matches this description and you cannot authenticate, try this rule in public/.htaccess (replace the plain one):
RewriteRule ^(.*)$ index.php [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
Method _authenticateWithHttpBasic (line 2715)
Method _authenticationRequest (line 2799)
Method _callFilters (line 1992)
Method _canApplyLayout (line 1432)
Method _conditionArray (line 1935)
Method _doubleRenderError (line 1028)
Method _encodeCredentials (line 2794)
Method _ensureFilterRespondsToBeforeAndAfter (line 1908)
Method _extractConditions (line 1915)
Method _hasTemplate (line 1054)
Method _isCandidateForLayout (line 1437)
Method _isSslRequired (line 2348)
Method _isTemplateExemptFromLayout (line 1065)
Method _paginationCountCollection (line 2285)
Method _paginationCreateAndRetrieveCollections (line 2266)
Method _paginationFindCollection (line 2295)
Override this method to implement a custom finder.
Method _paginationLoadPaginatorAndCollection (line 2310)
Method _paginationValidateOptions (line 2209)
Method _pickLayout (line 1444)
Method _prependFilterToChain (line 1903)
Method _removeModuleNameFromControllerName (line 870)
Method _requestHttpBasicAuthentication (line 2720)
Method _rewriteAuthentication (line 1141)
Method _rewriteUrl (line 1112)
Method _skipFilter (line 1840)
Method _templateIsPublic (line 1059)
Method __getControllerName_PHP4_fix (line 847)
AkObject::AkObject() - A hack to support __construct() on PHP 4
AkObject::__construct() - Class constructor, overriden in descendant classes
AkObject::freeMemory() - Unsets circular reference children that are not freed from memory when calling unset() or when the parent object is garbage collected.
AkObject::log() -
AkObject::toString() - Object-to-string conversion
AkObject::__clone() - Clone class (Zend Engine 2 compatibility trick)
AkObject::__destruct() - Class destructor, overriden in descendant classes
AkObject::__toString() -