Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / Какие замечания по стилю кода / 5 сообщений из 5, страница 1 из 1
10.05.2012, 00:33:18
    #37787133
Няша ррр
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Какие замечания по стилю кода
Код: php
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.
$actions = array(
    'create_page',
    'edit_page'
);

$menu = array(
    'create_page'
);

$titles['create_page'] = 'Создать страницу';
$titles['edit_page'] = 'Редактировать страницу';

function page_form($id = null, $alias = null, $title = null, $keywords = null, $description = null, $content = null) {
    global $js_arr;
    
    require_once '../lib/forms.php';
     
    $js_arr[] = '../js/page_form.js';
    
    $out = '';
    $out .= '<div id="response"></div>';
    $out .= begin_form('page-form', 'fields');
    $out .= hidden_field('id', $id);
    $out .= '<p>' . text_field('alias', 'Имя:', $alias);
    $out .= '<p>' . text_field('title', 'Заголовок:', $title);
    $out .= '<p>' . text_field('keywords', 'Ключевые слова:', $keywords);
    $out .= '<p>' . text_box('description', 'Описание:', $description);
    $out .= '<p>' . text_box('content', 'Содержимое:', $content, 10);
    $out .= '<p>' . button('send', 'Сохранить');
    $out .= '</form>';
    return $out;
}

function create_page() {   
    return page_form();
}

function edit_page() {
    global $db;
    
    $page = $db->find('pages', $_GET['id']);
    
    if ($page) {
        extract($page);
        return page_form($id, $alias, $title, $keywords, $description, $content);
    }
    return '<p>Страницы не сущетствует.</p>';
}



Код: php
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.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
<?php

error_reporting(E_ALL);

require_once '../lib/magic_quotes_off.php';
require_once '../lib/bootstrap.php';
require_once '../lib/functions.php';

$response = new stdClass;
$response->message = '';
$response->error = true;

try {   
    require_once '../lib/connect.php';
    
    if ($_POST) {
        $id = intval($_POST['id']);
        $alias = strtolower($_POST['alias']);
        $title = trim($_POST['title']);
        $keywords = trim($_POST['keywords']);
        $description = trim($_POST['description']);
        $content = $_POST['content'];
        
        if ($id && $db->countAll('pages', 'id = ' . $id) == 0) {
            $response->message = 'Вы пытаетесь редактировать несуществующую страницу.';
        }
        else if ($alias == '') {
            $response->message = 'Введите имя страницы.';
        }
        else if (preg_match('/\w{1,64}/i', $alias)) {
            $check_alias = true;
            
            if ($id) { // При редактирование, если новый алиас совпадает со старым, не выполняем проверку на наличие страницы с таким алиасом.
                $current_alias = $db->fetchOne('pages', 'alias', 'id = ' . $id);
                $check_alias = $alias !== $current_alias;
            }
            
            if ($check_alias && $db->countAll('pages', 'alias = ' . $db->quote($alias))) {
                $response->message = 'Страница с таким именем уже существует.';
            }
            else if ($title == '') {
                $response->message = 'Введите заголовок страницы.';
            }
            else {
                $title = preg_replace('/\s{2,}/s', ' ', $title);
                $keywords = preg_replace('/\s{2,}/s', ' ', $keywords);
                $description = preg_replace('/\s{2,}/s', ' ', $description);   
                $page = compact('alias', 'title', 'keywords', 'description', 'content');               
                $id ? $db->update('pages', $page, $id) : $db->insert('pages', $page);
                $response->message = 'Сохранено.';
                $response->error = false;
            }
        }
        else {
            $response->message = 'Недопустимое имя.';
        }
    }
    else {
        $response->message = 'Hacking attempt!'; // Бугого
    }
}
catch (Exception $e) {
    $response->message = $e->getMessage();
}

echo(json_encode($response));

?>



Код: javascript
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.
function showResponse(response) {
    var container = ge('response');
    container.innerHTML = '';
    var div = document.createElement('div');
    div.className = response.error ? 'error' : 'success';
    div.innerHTML = response.message;
    container.appendChild(div);
}

window.addEventListener('load', function() {
    var form = ge('page-form'),
        send = ge('send'),    
        label = send.innerHTML,
        loader = new Image(); 
    
    loader.src = '../images/ajax-loader.gif';

    send.onclick = function() {       
        var page = {
            id: val('id'),
            alias: val('alias'),
            title: val('title'),
            keywords: val('keywords'),
            description: val('description'),
            content: val('content')
        };   
        
        send.innerHTML = '';
        send.appendChild(loader);
        send.disabled = true;     
        
        var xhr = new XMLHttpRequest();
        
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4){              
                if (xhr.status == '200') {
                    eval('var response = ' + xhr.responseText);
                    showResponse(response);
                    
                    if (!response.error) {
                        window.location.search = '?action=page_list';
                    }
                }
                else {
                    alert('Error ' + xhr.status + ': ' + xhr.statusText);
                }
                
                send.innerHTML = label;
                send.disabled = false;
            }
        }

        xhr.open('POST', '../ajax/save_page.php');
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // Иначе не отправится     
        xhr.send(buildQuery(page));
        return false;
    }
}, false);
...
Рейтинг: 0 / 0
10.05.2012, 00:37:37
    #37787134
Няша ррр
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Какие замечания по стилю кода
Код: javascript
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
var elementsCache = {}; // кэш элементов

function ge(id) {
    if (elementsCache[id] === undefined) {
        elementsCache[id] = document.getElementById(id);
    }
    return elementsCache[id];
}

function val(id, value) {
    var el = ge(id);
    
    if (value === undefined) {
        return el.value;
    }

    el.value = value;
}
...
Рейтинг: 0 / 0
10.05.2012, 00:52:16
    #37787136
Няша ррр
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Какие замечания по стилю кода
Код: php
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.
<?php

error_reporting(E_ALL);

require_once '../lib/magic_quotes_off.php';
require_once '../lib/bootstrap.php';
require_once '../lib/functions.php';
require_once '../lib/admin.php';
require_once '../lib/template_vars.php';

try {
    require_once '../lib/connect.php';
    
    $action = isset($_GET['action']) ? $_GET['action'] : null;
    
    if (function_exists($action)) {
        $title = $titles[$action];
        
        $css_arr[] = '../css/common.css';
        $css_arr[] = '../css/admin.css';
        $js_arr[] = '../js/common.js';
        
        $content = call_user_func($action);
                      
        require 'template.php';       
    }
    else {
        throw new Exception("Action $action does not exists.");
    }   
}
catch (Exception $e) { 
    echo($e->getMessage()); // На рабочес сайте ест-но никакие ошибки выводится не будут
    // Например, будем происходить логирование
    // file_put_contents('../logs/error.txt', $e->getMessage() . "\r\n", FILE_APPEND | LOCK_EX);
}

?>
...
Рейтинг: 0 / 0
10.05.2012, 02:21:06
    #37787154
Какие замечания по стилю кода
javascript ajax
Код: php
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.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
(function(A){
    A.contains = function(value){
        var max = this.length,
            i = 0;
        for(i; i < max; i += 1) {
            if (this[i].toLowerCase() === value.toLowerCase()) {
                return true;
            }
        }
        return false;
    }
})(Array.prototype)

var console = window.console || {
    log : function(msg) {
        alert(msg);
    }
},
MYAPP = MYAPP || {};

MYAPP.ajax = function(url, callback, method, data, async){
    var _url = typeof(url) === 'string' ? url : null,
    _callback = typeof(callback) === 'function' ? callback : function(){},
    _method = [
        'GET',
        'HEAD',
        'POST',
        'DELETE',
        'PUT',
        'OPTIONS'
    ].contains(method) ? method : 'GET',
    _data = typeof(data) === 'string' ? data : '',
    _async =  typeof(async) === 'boolean' ? async : true,
    xmlHttp = null;

    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                xmlHttp = null;
            }
        }
    } else if (window.createRequest) {
        try {
            xmlHttp = window.createRequest();
        } catch (e) {
            xmlHttp = null
        }
    };

    if(xmlHttp && _url){
        xmlHttp.open(_method, _url, _async);
        xmlHttp.onreadystatechange = function() {
            if (this.readyState === 4) {
                _callback(this.responseText, this.status);
            }
        };
        if(_method === 'POST'){
            xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xmlHttp.setRequestHeader('Content-length', _data.length);
            xmlHttp.setRequestHeader('Connection', 'close');
        }
        xmlHttp.send(data);
    }
};


Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
MYAPP.ajax(
      'url',
      function(data, status){
             switch(status)
             {
                  case 200:
                       console.log(data);
                       break;
                  case 202:
                       //console.log(data);
                       break;
                  default:
                       console.log(status);
                  }
             },
       'POST',
       'data=' + encodeURIComponent(JSON.stringify([{}])))
);


PHP
Код: php
1.
$action = isset($_GET['action']) ? $_GET['action'] : null;


===
Код: php
1.
$action = & $_GET['action'];


and etc.

Успехов!!!
...
Рейтинг: 0 / 0
10.05.2012, 13:35:28
    #37787763
Ренат
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Какие замечания по стилю кода
Няша ррр,

1. HTML в PHP коде - некрасиво (ps. ShSerge, пожалуйста без коментариев)
2. генераторы форм и их валидация советую поглядеть в любом фреймворке
...
Рейтинг: 0 / 0
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / Какие замечания по стилю кода / 5 сообщений из 5, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]