Получение action запроса

Posted декабря 30, 2009 in CodeIgniter, Рецепты by SpiRi7

Еще одна полезная функция взятая из фреймворка CodeIgniter.
Задача функции проста – получить составляющие запроса.
Например:
Наш сайт находится по адресу http://site.com/somedir/. Мы используем url_rewrite для получения красивых адресов. Все управление происходит через index.php. Производится запрос к адресу http://site.com/somedir/someaction/somemethod. Необходимо получить “someaction” и “somemethod”.
Код функции которая выполняет нашу задачу:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
/**
 * Example of use 
 */
function testFunctionCall() {
   $result = get_request_action();
   print_r($result);
}
/**
 * Get current action for selected query
 */
function get_request_action() {
    $action = parse_url(parse_request_uri());
    $folder = explode('/', $action['path'], 4);
 
    $action = (isset($folder[1]) ? htmlspecialchars(strip_tags($folder[1])) : '');
    $folder = (isset($folder[2]) ? htmlspecialchars(strip_tags($folder[2])) : '');
    return array($action,$folder);
}
 
/**
 * Parsing request url and get uri with current server dir
 * @return <type>
 */
function parse_request_uri() {
    if ( ! isset($_SERVER['REQUEST_URI']) OR $_SERVER['REQUEST_URI'] == '') {
        return '';
    }
 
    $request_uri = preg_replace("|/(.*)|", "\\1", str_replace("\\", "/", $_SERVER['REQUEST_URI']));
 
    if ($request_uri == '' OR $request_uri == SELF) {
        return '';
    }
 
    $fc_path = __FILE__;
    if (strpos($request_uri, '?') !== FALSE) {
        $fc_path .= '?';
    }
 
    $parsed_uri = explode("/", $request_uri);
 
    $i = 0;
    foreach(explode("/", $fc_path) as $segment) {
        if (isset($parsed_uri[$i]) && $segment == $parsed_uri[$i]) {
            $i++;
        }
    }
 
    $parsed_uri = implode("/", array_slice($parsed_uri, $i));
 
    if ($parsed_uri != '') {
        $parsed_uri = '/'.$parsed_uri;
    }
 
    return $parsed_uri;
}
?>

После вызова функции testFunctionCall() мы получим что то вроде
Array ( [0] => "someaction" [1] => "somemethod" )

Простой шаблонизатор, CI view

Posted декабря 30, 2009 in CodeIgniter, Рецепты by SpiRi7

Для того что бы хорошо разбираться в предметной области необходимо понимать как работает тот или иной механизм.
Если копнуть в глубь исходников CodeIgniter, можно найти способ, с помощью которого авторы этого фреймворка производят загрузку view.
Ниже находится код который можно использовать в своих проектах, он не использует никаких классов и переменных из фреймворка CodeIgniter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
	/** Функция производит загрузку отображения, передачу в него параметров.
	 *  Возвращает полученный html код
	 */ 
	function loadTemplateView($view, $vars = array())
	{
		return _ci_load_view(array('_ci_view' => $view, '_ci_vars' => $vars));
	}
 
	/**
	 * View Loader
	 */
	function _ci_load_view($_ci_data)
	{
                /* You need to move this variable to your config file */
                $template_dir = "http://site.com/template";
 
		// Set the default data variables
		foreach (array('_ci_view', '_ci_vars', '_ci_path') as $_ci_val)
		{
			$$_ci_val = ( ! isset($_ci_data[$_ci_val])) ? FALSE : $_ci_data[$_ci_val];
		}
 
		// Set the path to the requested file
		$_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION);
		$_ci_file = ($_ci_ext == '') ? $_ci_view.EXT : $_ci_view;
		$_ci_path = $template_dir."/".$_ci_file;
 
		if ( ! file_exists($_ci_path))
		{
			echo 'Unable to load the requested file: '.$_ci_file."<br>";
		}
                extract($_ci_vars);
 
                /* Start buffer the output */
		ob_start();
 
		include($_ci_path); 
 
		// Return the file data
                /* Buffered output to variable */ 
		$buffer = ob_get_contents();
		@ob_end_clean();
		return $buffer;
	}
 
        function example_use() {
                $data = array();
                $data['news_list'] = "SomeTestValue";
                $header = loadTemplateView('news.tpl',$data);
        }
?>

Достаточно просто и очень актуально для небольших проектов.