Перейти к основному содержанию
Тема: Руководство по разработке (Прочитано 3886 раз) предыдущая тема - следующая тема

Руководство по разработке

Руководство по написанию кода для разработчиков модов SMF

Sorry за мерзкий перевод...
Я взял на себя смелость и вообще перевёл некоторые предложения по своему  8)
Оригинал здесь

В целях повышения читаемости, и чтобы снизить риск ошибок и улучшить общую производительность, набор руководящих принципов кодирования используются для кода в SMF. Многие из этих руководящих принципов описанны в данном документе. Пожалуйста, постарайтесь придерживаться их как можно больше при написании модификаций для SMF или даже шаблоны проектирования, так что другие люди могут лучше работать с вашим кодом.

Руководство по принципам правильного кодирования
Это - краткий обзор руководящих принципов правильного кодирования.

Кодекс PHP
  • Избегайте использование глобальных переменных в своём коде, когда это возможно, попытайтесь держать все переменные в локальной/статичной области.
  • Не используйте функции, которые не существуют в PHP 4.1.0 (и не использовать функции, которые были удалены позже тоже!), если вы определите их для этих версий они отсутствуют дюйма.
  • не используйте функции, которые не существуют в PHP 4.1.0 (также не используйте функции, которые были удалены позже!), если Вы их сами не определите.

    MySQL
  • Избегайте имен полей и псевдонимов столбцов, которые являются ключевыми словами в MySQL.
  • Не используйте функции MySQL, не доступные в MySQL 3.23.28 и выше.
  • Конструкции LEFT JOIN регулярно медленнее, чем JOIN, поэтому их нужно избегать, если это возможно.
  • Используя JOIN, столбцы таблиц, к которым присоединяются, должны быть на первом месте в пунктах ON.

    Таблицы базы данных и колонки
  • не делайте приставки, каждая колонка в столе с определенной приставкой - использует псевдонимы стола вместо этого (иначе, Вы только делаете имена дольше, насильственно. )
  • Никогда не используйте По умолчанию и auto_increment вместе.
  • не делайте имен ключа приставки с idx _; вместо этого, предпочтите название колонки, которую они вносят в указатель, или описательное имя того, что они вносят в указатель.
  • Комментарии размещайте не внутри запроса(нагрузка на память сервера), а вне его.

    Общий
  • Мы не нуждается в функциональности, которую не будут использовать большинство людей. (Не делайте моды, которые никому не нужны)

    Руководство по принципам правильных макетов
    Шаблоны
  • no queries or "advanced" code should ever be used in the default templates (and should be avoided in other themes.)
  • if possible, any changes to the "main" templates (index, BoardIndex, Display, MessageIndex) should not be required for continued operation.
  • don't use abbreviations in $context index names, except when completely clear.
  • do not use heredoc or print(), but rather echo with single quotes if the text is long with few variables.
  • when outputting something using echo, use commas to pass variables as separate parameters. (echo 'foo', $bar, 'foobar'; )
  • avoid making any template changes between minor releases.
  • when a large number of checkboxes are shown, include a "check all" option.
  • make sure the indents of the PHP code and the HTML code are correct. Both indent independently.

    Документация и комментарии
  • Храните корректную документацию в вершинах файлов.
  • Документация в начале файлов ограничивается шириной 80 символов.
  • Не дублируйте документацию(таким образом, они могут разыскиваться уникально).
  • Начало каждой строки комментария с большой буквы, и использовать соответствующую грамматику (точки в конце и все!)
  • Пользуйтесь // комментариями вместо /* комментарии */, когда это возможно, например, когда комментарий размещается на одной строке.
  • Пользуйтесь комментариями подобно *соли и перцу(?это у хранцузов, видать, такой прекол?)*: комментарии закаляют ваш код, так что другие, смотря на ваш код, лучше понимают его.

    Использование отступов
  • Не бойтесь использовать пустые строки между логическими "разделами" кода, но не использовать слишком многих, потому что он делает его слишком растянутым.
  • В запросах или коде, всегда имейте пробелы перед и после операторов.
  • Для добавления отступа всегда используйте единственную позицию табуляции на отступ. Для лучших результатов используйте вкладку шириной 4 символа.
  • Перед открывающей или закрывающей фигурной скобкой делайте перевод строки. ({/})
  • Не используйте фигурные скобки когда они ненужны, кроме случаев, где есть много операторов, вложенных друг в друга.
    Другими словами, используйте следующий синтаксис:
    // Above we set $php_seems_weird to true if something seems strange...
    if ($php_seems_weird)
    {
       // This is not good, seems PHP might be broken!
       if (1 + 1 != 2)
          trigger_error('This version of PHP seems to be very broken', E_USER_ERROR);
    }


    HTML, CSS, and Javascript
  • Всегда ставьте атрибут alt на все элементы изображения, даже если alt пуст.
  • only specify alt text when you really would prefer text to be there if the image went missing or in textual browsers - do not use it to describe every image (that's what title's job is.)
  • Код в файле script.js используется ГЛОБАЛЬНО  для ВСЕХ тем, а не только для дефолтной темы. (в отличии от файла style.css.)
  • always close input, img, hr, and other elements that can't contain anything. (<name />)
  • do not use multiple class names in the class attribute, even though this is in the spec; instead use extra divs or spans (please note, this may be changed in SMF 1.1.)
  • always use style="check" on input[type="radio"] and input[type="checkbox"].
  • unless under special circumstances, outside links should open using the target "_blank", and all others with no target.
  • keep all id attributes unique within page views, and try to keep id and name the same if both are specified.

    Основы написания модификаций
    1. SQL Changes

    As a general rule of thumb mods should not alter the name, size or index of any table which is created as part of an SMF default installation - unless of course it is a mod whose aim is to enhance performance in some way. Instead it is assumed that mods will generally only add new tables, or otherwise add new columns to existing tables. If it is essential for a modification to alter the default SMF structure then it must provide, as part of the uninstall script, a means to put the tables back to their original form. The reason behind this is to ensure that as the user upgrades SMF in the future, that upgrades do not fail as a result of your modification.

    If you have added your own tables and columns it is probably inappropriate to remove this structure upon uninstallation of the mod - as all collected data will be lost. The reason behind this is simply that many users may uninstall a modification due to an upgrade, and be upset at the loss of data. If you are determined to remove the structure upon uninstallation then please do so providing a separate package so the user is fully aware of what is being carried out in their database.

    2. Version Unspecific Mods

    Using the package manager it is possible to define different installation methods dependant on the version of SMF someone is running. This makes it possible to have a mod which would install on (for example) SMF 1.0 and also install on SMF 1.1 Beta 2, even though the actual changes are different. This is achieved by adding a "for" attribute to the package-info.xml file included with all package manager mods. So, to define a set of install actions for SMF 1.0 you would use the install tag as:

    <install for="SMF 1.0">


    If an install tag is encountered without the "for" attribute then it will be followed regardless of the current version. SMF follows install tags like an if/else statement, it will look at each set of installation tags in turn until it finds one it matches. The last set of install tags in a package should always be left without a "for" attribute set. This ensures that if your package is used on a future version of SMF, then some installation actions will exist. This is best shown with an example, a basic example of a possible package structure, with most tags missing is:


    <install for="SMF 1.0 Beta 6, SMF 1.0 Beta 6 Public">
      <modification file="mod_actions_b6.xml" />
    </install>
    <install for="SMF 1.0">
      <modification file="mod_actions_1_0.xml" />
    </install>
    <install>
      <modification file="mod_actions_1_1.xml" />
    </install>


    With a package like above, SMF will go through each set of tags, trying to find a set which match the current version. If by the last set of tags no version has been found, it will attempt to run the actions in the final set (Here mod_actions_1_1.xml). In this example that means anyone running SMF 1.1, 2.0 or 5.2 could still attempt to install the modification. Note exactly the same method is true for uninstall actions.

    to be continued/перевод не завершён(будет время - продолжу)