Coding Guidelines

Hier meine Zusammenfassung der TYPO3 Coding Guidelines

Allgemein

Sprache: Englisch
Einfache Anführungszeichen
Dateiname < 31 Zeichen lowercase
Javadoc Kommentare max. 80 Zeichen
SQL Keywords: Uppercase
Tabellennamen: Lowercase
Klassen inkludieren mit:  require_once()
Andere Files inkludieren: include()

Header

Copyright Vermerk

/***************************************************************
 *  Copyright notice
 *
 *  (c) 2007 Erwin Knoll <typo3coding@example.com>
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

 

Klassen

Eine Klasse pro Datei

Name

Benennung: class.[classname].php - classname in lowercase
Classname:
  Prefix: tx_
  Prefix für XCLASS Erweiterungen: ux_
  Prefix 2: Extension-Name ohne "_" mit "_" am Ende
  Name: mixedCase mit Kleinbuchstabe beginnend

Variablen

Variablen in Klassen mixedCase

Javadoc Kommentar

/**
 * Plugin 'Geo Search' for the 'rsys_geosearch' extension.
 *
 * $Id$
 * @author      Erwin Knoll <typo3coding@example.com>
 * @package     TYPO3
 * @subpackage  tx_rsysgeosearch
 */

 /**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 */

$id$: Wird beim Checkin in das TYPO3 Repository ersetzt
@author: Name und Email
@package: Ist immer TYPO3
@subpackage: Extension key ohne "_"
[CLASS/FUNCTION INDEX of SCRIPT]: Wird von extdeveval ersetzt

Footer

XCLASS Include

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/rsys_geosearch/pi1/class.tx_rsysgeosearch_pi1.php'])    {
 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/rsys_geosearch/pi1/class.tx_rsysgeosearch_pi1.php']);
}

Methoden

Javadoc Kommentar


/**
 * Initialization - create the Content Object
 *
 * Used when the plugin is not placed on a page but created
 * manually by $cObj = t3lib_div::makeInstance('tx_rsysgeosearch_pi1');
 *
 * @param    array        Key/value pairs of configuration values
 * @return   boolean      If true, no error occured  
 *
 * @access private
 * @see checkCommentQuality()
 */
 function init($conf)

Name

mixedCase, wenn gewünscht mit "_"

Erstellt: 07/2010| Geändert: 10/2015

Variablen und Konstanten

Globale Variablen

Uppercase

GET und POST

Möglichst in init()  alles externen Input einlesen und in Klasse speichern.
Name: Extensionkey ohne "_" als Array tx_myext[email]

Zugriff:

  • t3lib_div::_GET()
  • t3lib_div::_POST()
  • t3lib_div::_GP() - Priorität POST

Rückgabe ist immer unescaped

System/PHP Variablen

Zugriff mit  t3lib_div::getIndpEnv()

Erstellt: 07/2010| Geändert: 10/2015

Datenbank

Rückgabewerte sind Objekte und müssen an Funktionen immer per Referenz übergeben werden!
Alle Werte in WHERE clauses mit  $GLOBALS['TYPO3_DB']->fullQuoteStr($varname, $tableName)
JOIN: Feldnamen mit Tabellen-Prefix
Keine boolean Auswertung von Integerwerten (AND test=0 statt AND test)
Negation operator: Nicht ! verwenden
AS Keyword: Für Felder ok, aber nicht für Tabellen!

Wrapper Funktionen Backend

Queries ausführen

$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, 'SELECT * FROM mytable');
while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
    echo $row['title'].'<br />';
}

Queries erstellen

// SELECT:
$query = $GLOBALS['TYPO3_DB']->SELECTquery(
                '*',                                  // SELECT ...
                'mytable',                            // FROM ...
                'uid=123 AND title LIKE "%blabla%"',  // WHERE...
                '',                                   // GROUP BY...
                'title',                             // ORDER BY...
                '5'                                  // LIMIT ...
            );

// INSERT:
$insertArray = array(
    'pid' => 123,
    'title' => "My Title"
);
$query = $GLOBALS['TYPO3_DB']->INSERTquery('mytable', $insertArray);

// UPDATE:
$updateArray = array(
    'title' => "My Title"
);
$query = $GLOBALS['TYPO3_DB']->UPDATEquery('mytable', 'uid=123', $updateArray);

// DELETE
$query = $GLOBALS['TYPO3_DB']->DELETEquery('mytable', 'uid=123');

Für den Where clause:

t3lib_BEfunc.BEenableFields($table, $inv = 0)
t3lib_BEfunc.deleteClause($table, $tableAlias = '') 

Queries erstellen und ausführen

Wie oben nur mit exec_ Prefix

$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(...

Frontend

Queries im Frontend ausführen:

// UPDATE, INSERT, DELETE: Associatives Array anlegen
// and enable the doExec flag if you can so the query is executed directly!
tslib_cObj::DBgetUpdate($table, $uid, $dataArr, $fieldList, $doExec=FALSE)
tslib_cObj::DBgetInsert($table, $pid, $dataArr, $fieldList, $doExec=FALSE)
tslib_cObj::DBgetDelete($table, $uid, $doExec=FALSE)


// SELECT : No general API

Erstellt: 07/2010| Geändert: 10/2015

Security

XSS - Cross Site Scripting

Allen HTML Output durch htmlspecialchars(§content) parsen. Wenn man nicht alle HTML Tags entfernen will kann man  strip_tags($content, '<b><i>') nehmen (hier würden <b> und <i> erhalten bleiben).

In TypoScript hat stdWrap die Eigenschaft removeBadHTML um bekannten Schadcode zu entfernen.

Noch besser ist es nur gezielt Buchstaben und Zahlen zuzulassen.

SQL Injection

Werte die in SQL Statements eingefügt werden, parsen mit $GLOBALS['TYPO3_DB']->quoteStr() oder intval() - so nahe an der SQL wie möglich. Wenn die Werte aus GET oder POST Daten kommen die Funktionen t3lib_div::_GET(), t3lib_div::_POST() oder t3lib_div::_GP() verwenden.

Immer Anführungszeichen in SQL Werten verwenden (ausser es ist sicher ein Integer Wert).

Pfade

Pfade immer validieren mit t3lib_div::validPathStr($path)

Absoluten Pfad prüfen: t3lib_div::isAllowedAbsPath()
Absoluten Pfad aus relativen: t3lib_div::getFileAbsFileName()

Erstellt: 07/2010| Geändert: 10/2015

TYPO3 spezifisch

TCA

Aufruf von t3lib_div::loadTCA($tablename) vor Benutzung des $TCA Arrays - ausser bei der [ctrl]-Sektion

PHP Variablen

t3lib_div::getIndpEnv() um Variablen wie REQUEST_URI oder REMOTE_ADDR oder SCRIPT_FILENAME zu lesen.

Objekte erzeugen

t3lib_div::makeInstance($className)

Textarea

Inhalt für ein <textarea> Feld mit t3lib_div::formatForTextarea()

Backend

$TBE_TEMPLATE->formWidth() für Input, $TBE_TEMPLATE-
>formWidthText()
für textarea Felder

Javascript HTML Tags

t3lib_div::quoteJSvalue($value, $inScriptTags).

inScriptTags = true: Verwendung in <script> tags
inScriptTags = false: Verwendung in Attribut eines Tags (z.B: onClick)

Erstellt: 07/2010| Geändert: 10/2015

PHP Namenskonventionen

Variablen Namen: Mixed case, Start mit lowercase

$sTitel, $iSizeOfSomething, ...

a Array
b bool
i int
d double
f float
l long
s string
g_ global (gefolgt von weiterem prefix)

Boolean: b gefolgt von is, has, can or should

$bIsActive, $bHasName

Ebenso für Funktionen mit boolschen Rückgabewert - aber ohne b prefix

$user->hasAddress();

Objekte lowercase -oder- Prefix o oder obj

$user,  $page
$oUser, $objPage

Konstanten: Uppercase mit Underscores

$PAGES_LIMIT, $PATH

Funktionen: Mit Verb beginnen, mixed case, Erster Buchstabe lower case

getUser(), fetchArray()

SQL keywords: uppercase

SELECT * FROM users  

Objektname nicht in der Methode wiederholen

$session->getId() // Nicht: $session->getSessionId()

Methoden die Attribute setzen: get/set

$user->getId()
$user->setId($iId)

Erstellt: 07/2010| Geändert: 10/2015