Thread for sharing of snippets. Commenting your code and following the CodingStyle is encouraged, but not required.
Please do not ask for assistance with pastes, this is not meant to be a support thread. All snippets are for demonstration purposes only!
All pastes are considered public domain, unless a copyright header is in the code.
Paste away!
Here is an example of an extended controller being used as a CRUD tool for an ORM User_Model. (Using Kohana from SVN)
Example of validating uploads using Validation and the upload:: helper. (SVN)
don't know if this is the right place to comment the snippets, if it's not please tell me anyway, in your Users_Controller at row 36 (function detail) you have this code: $user = $this->get_user($id); i suppose get_(model) is a function in your Base_Controller which takes the model given in function name after the underscore, loads it & get the record identified by id. Am i correct? Can you post the code? (i can understand such a behavior in theory but never done it)
Thank
Posted By: phelzdon't know if this is the right place to comment the snippets, if it's not please tell me
anyway, in your Users_Controller at row 36 (function detail) you have this code:
$user = $this->get_user($id);
i suppose get_(model) is a function in your Base_Controller which takes the model given in function name after the underscore, loads it & get the record identified by id.
Am i correct? Can you post the code? (i can understand such a behavior in theory but never done it)Thank
uops! didn't saw that... sorry
simple ajax helper to handle ajax responses
$lf = new LastFM;
$auth_url = $lf->get_auth_url(); // get a token and the url for user authorization
$lastfm_token = $lf->get_config('token'); // retrieve the token for backend storage to call after user authorization at $auth_url
$this->session->set('lastfm_token', $lastfm_token);
$lf = new LastFM;
$lastfm_token = $this->session->get('lastfm_token'); // get the user application token
$lf->set_config('token', $lastfm_token); // set the token in the lastfm object
$lf_session = $lf->get_session(); // retrieve the authorized user session
$this->session->set('lastfm_sk', $lf_session); // store the authorized session
$this->session->delete('lastfm_token'); // token no longer needed
$lf = new LastFM;
$lastfm_sk = $this->session->get('lastfm_sk'); // retrieve the authorized user session key
$lf->set_config('sk', $lastfm_sk); // set the session key in our object
$lastfm_userdata = $lf->call('user.getinfo', '', 'user'); // perform an authenticated api request
continuing the work dlib's started with jquery and forge, i've slightly modified the code to extend the validation library in Kohana 2.2.
Just drop MY_Validation.php inside your application library folder and use it like this example
Posted By: alain91Hye,
Posted By: cecplexAnswering my own question because Google is awesome! :) The new URL is here:http://kohanaphp.com/resources/video/page_cache_hook.mov
@Mabogie: You can do this without the page_cache hook. Just use the Cache library to set and get the raw data you'd like to cache as to prevent your scripts from running the query.
I propose a code to manage the cache and let the process of Kohana terminates to be compatible with the display of execution times and other modules or lib whch use 'system.displat' event.
I hope this will help.
PS: Does anyone have an explanation if call argument in callback have to be value or reference for optimisation
<?php defined('SYSPATH') or die('No direct script access.');</p>
/**
*
* Author : Alain91 on Kohana Forum
*
*/
class Hook_page_cache
{
private $cache;public function __construct()
{
$this->cache = new Cache();
Event::add('system.post_controller_constructor', array(&$this, 'load_cache'));
}public function load_cache()
{
$id = session_id();
if (!empty($id)) return; // probleme with trans_sid mode in files in cache$cache = $this->cache->get('Page_'.$tmp);
if ( $cache ) {
// Stop the controller setup benchmark
Benchmark::stop(SYSTEM_BENCHMARK.'_controller_setup'); // due to the step where Cache is loaded in the process// Start the controller execution benchmark
Benchmark::start(SYSTEM_BENCHMARK.'_controller_execution');// load the ob_start buffer
echo $cache;
// add event 'system.display' eventualy to fill some user variables like kohana render()// Stop the controller execution benchmark
Benchmark::stop(SYSTEM_BENCHMARK.'_controller_execution');
//Jump to normal end
Kohana::shutdown();
// To avoid exucetion of shutdown twice (bootstrap.php'
exit;
} else {
// inssert event in head of the event list (to save the file with kohana variables or user variables
MY_Event::add_first('system.display', array(&$this, 'save_cache'));
}}
public function save_cache()
{
$this->cache->set('Page_'.url::current(), Event::$data);
}}
new Hook_page_cache;
<?php defined('SYSPATH') or die('No direct script access.');
class Environment {
//Holds the environment data
static public $TYPE;
/**
* Called to grab config data on the system.ready event
*
* @access public
* @param void
* @return void
*
**/
static public function setup(){
self::$TYPE = Kohana::config('environment.current');
}
}
Event::add('system.ready', array('Environment', 'setup'));
?>
<?php defined('SYSPATH') or die('No direct script access.');
$config['current'] = 'DEVELOPMENT';
<?php defined('SYSPATH') or die('No direct script access.');
$config = array(
'DEVELOPMENT'=> 'development_key_here',
'PRODUCTION'=> 'production_key_here',
);
<script src="http://maps.google.com/maps?file=api&v=2&key=<?= Kohana::config('googlemaps.'.Environment::$TYPE); ?>" type="text/javascript"></script>
@themusicman, I think you're making things a bit harder. What about something like
googlemaps.php config file
<?php defined('SYSPATH') or die('No direct script access.');
$config['key'] = (IN_PRODUCTION) ? 'production_key_here' : 'development_key_here';
view file
<script src="http://maps.google.com/maps?file=api&v=2&key=<?=Kohana::config('googlemaps.key')?>" type="text/javascript"></script>
Your solution solves the problem if you have more than two enviroments, but Kohana has the IN_PRODUCTION constant defined on index.php and can be used to simplify the whole thing on a development/production scenario.
<?php
/**
* Class to display Google Analytics code.
*
* 1 step required to setup the class (see below)
*
* @example echo GoogleAnalytics::get();
*
*/
class GoogleAnalytics
{
/* STEP 1: Define each domain and it's corresponding tracker code */
private static $DOMAINS = array(
'example.library.dev' => 'UA-1111111-11', /* leave out the www. for each domain if STRICT = false */
'staging-url.com' => 'UA-2222222-22', /* lowercase only */
'development-url.com' => 'UA-3333333-33',
'production-url.com' => 'UA-4444444-44',
'example.com' => 'UA-5555555-55',
);
/* whether or not to treat www.example.com and example.com identically */
const STRICT = FALSE;
/**
* Is our domain in the allowed list
*
* @return Boolean
*/
public static function enabled()
{
$domain = self::domain();
return (in_array($domain,array_keys(self::$DOMAINS)));
}
/**
* Retrieve current domain
*
* @return String
*/
public static function domain()
{
$domain = strtolower($_SERVER['HTTP_HOST']);
if (self::STRICT) {
return $domain;
}
return preg_replace('/^www\./i','',$domain);
}
/**
* Retrieve google analytics code for a specific domain
*
* @return String
*/
public static function get()
{
$js = null;
$domain = self::domain();
if (self::enabled()) {
$tracker_code = self::$DOMAINS[$domain];
/* To update the code just remeber to put the tracker_code var back into the string */
$js =
<<<JAVASCRIPT
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("{$tracker_code}");
pageTracker._trackPageview();
</script>
JAVASCRIPT;
}
return $js;
}
}
/* This is pieces/category_list.php */
<ul>
<?php foreach($categories as $category): ?>
<li>
<?php echo $category->name; ?>
<?php if( $category->children ) View::factory('pieces/category_list')->set('categories', $category->children->as_array())->render(TRUE); ?>
</li>
<?php endforeach; ?>
</ul>
$config['admin'] = array
(
'admin/:controller/:method/:id',
// Will change all controllers to admin_:controller
'prefix' => array('controller' => 'admin_'),
);
$config['/admin/'] = array
(
'admin/:controller/:method/:id',
//! This must be set
'controller' => '',
// Will change all controllers to admin_:controller
'prefix' => array('controller' => 'admin_'),
);
if (isset($route['prefix']))
{
foreach ($route['prefix'] as $key => $prefix)
{
//!Makes sure that the controller index is set in the $config array
if (isset($route[$key]))
{
// Add the prefix to the key
$route[$key] = $route['prefix'][$key].$route[$key];
}
}
}
We already have this: date::timespan
Posted By: ShadowhandWe already have this:date::timespan
class Database extends Database_Core {
private static $results = array();
public function query($sql = '')
{
if( ! array_key_exists(md5($sql), self::$results[(int)$this->link]))
{
self::$results[(int)$this->link][md5($sql)] = parent::query($sql);
}
return self::$results[(int)$this->link][md5($sql)];
}
public function connect()
{
parent::connect();
if( ! array_key_exists((int)$this->link, self::$results))
{
self::$results[(int)$this->link] = array();
}
}
}
@avalanche123: Your extension is unnecessary, as this is what Database will do if you enable the cache option of your configuration group.
CREATE TABLE roles (
id serial NOT NULL,
name varchar(32) NOT NULL UNIQUE,
description varchar(255) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO roles (id, name, description) VALUES(1, 'login', 'Login privileges, granted after account confirmation');
INSERT INTO roles (id, name, description) VALUES(2, 'admin', 'Administrative user, has access to everything.');
CREATE TABLE roles_users (
user_id int NOT NULL,
role_id int NOT NULL,
PRIMARY KEY (user_id,role_id)
);
CREATE TABLE users (
id serial NOT NULL,
email varchar(127) NOT NULL UNIQUE,
username varchar(32) NOT NULL default '' UNIQUE,
password char(50) NOT NULL,
logins int NOT NULL default '0',
last_login int,
PRIMARY KEY (id)
);
CREATE TABLE user_tokens (
id serial NOT NULL,
user_id int NOT NULL,
user_agent varchar(40) NOT NULL,
token varchar(32) NOT NULL UNIQUE,
created int NOT NULL,
expires int NOT NULL,
PRIMARY KEY (id)
);
ALTER TABLE roles_users
ADD CONSTRAINT roles_users_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
ADD CONSTRAINT roles_users_ibfk_2 FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE;
ALTER TABLE user_tokens
ADD CONSTRAINT user_tokens_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
$head['meta'] = array('description' => 'Description of site',
'keywords' => 'key, words, for, site',
'author' => 'Corey');
$head['css'] = array('/css/styles.css' => 'screen',
'/css/print.css' => 'print');
$head['js'] = array('/js/jquery.js', '/js/jquery_ui.js', '/js/fancybox.js');
$this->template->head = $head;
</pre>
And then in my base template file:
<html>
<head>
<?php foreach ($head['meta'] as $key => $val) { ?>
<meta name="<?php echo $key; ?>" content="<?php echo $val; ?>" />
<?php }
foreach ($head['css'] as $key => $val) { ?>
<link rel="stylesheet" type="text/css" media="<?php echo $val; ?>" href="<?php echo $key; ?>" />
<?php }
foreach ($head['js'] as $val) { ?>
<script type="text/javascript" src="<?php echo $val; ?>"></script>
<?php } ?>
</head>
<body>
<?php echo $page; ?>
</body>
</html>
</pre>
So then later in my Controllers, I can simply add or remove what I need/don't need.
$this->template->head[js][] = '/js/new_script.js';
unset($this->template->head[css][1]);
</pre>
I'm creating a web API for an iPhone application and I found this useful.
MY_request.php:
<?php defined('SYSPATH') OR die('No direct access allowed.');
class request extends request_Core {
public static function is_iphone()
{
return (bool) (strpos(strtolower(Kohana::user_agent('agent')), 'iphone') !== false);
}
}
if (PHP_SAPI === 'cli')
// In CLI mode
// hooks/somehook.php
public function __construct() {
Event::add('system.ready', array($this, 'fill_configs'));
}
public function fill_configs() {
$configs = Kohana::config('database');
$default_size = count($configs['default']);
$default_connection_size = count($configs['default']['connection']);
$default_prefix = strlen($configs['default']['table_prefix']) > 0 ? $configs['default']['table_prefix'] : FALSE;
foreach ($configs as $name => $config) {
if ($name === 'default') continue;
if (count($config) != $default_size) {
$newconfig = arr::overwrite($configs['default'], $config);
$default_prefix !== FALSE AND $newconfig['table_prefix'] = $default_prefix.$newconfig['table_prefix'];
}
if (!isset($config['connection'])) {
$newconnection = $configs['default']['connection'];
}
elseif (count($config['connection']) != $default_connection_size) {
$newconnection = arr::overwrite($configs['default']['connection'], $config['connection']);
}
isset($newconfig) AND Kohana::config_set('database.'.$name, $newconfig);
isset($newconnection) AND Kohana::config_set('database.'.$name.'.connection', $newconnection);
}
}
// somewhere in modules/xxxmodule/config/database.php
$config['forum'] = array
(
'table_prefix' => 'forum_',
);
/**
* Index
*
* @return void
* @author Mathew
**/
public function index()
{
$this->template->content = View::factory('news/index');
// Total number of enabled news items.
$total = ORM::factory('news')->where('enabled', 1)->count_all();
// Pagination
$pagination = Pagination::factory(
array
(
'base_url' => Router::$controller.'/'.Router::$method,
'total_items' => $total
)
);
// Grab the news items.
$this->template->content->news = ORM::factory('news')
->where('enabled', 1)
->orderby('date_added', 'DESC')
->limit($pagination->items_per_page, $pagination->sql_offset)
->find_all();
// Pagination links
$this->template->content->pagination = $pagination;
}
It looks like you're new here. If you want to get involved, click one of these buttons!