Mastering Joomla! 1.5 Extension and Framework Development phần 2 potx

48 344 0
Mastering Joomla! 1.5 Extension and Framework Development phần 2 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 2 [ 35 ] When dealing with English characters, UTF-8 uses the same encodings as ASCII and ANSII. This has a purposeful consequence; UTF-8 encoded strings that use these characters appear identical to their ASCII and ANSII alternatives. Applications that are Unicode unaware are therefore able to handle many UTF-8 strings. One such application that is not Unicode aware is PHP. We therefore have to be careful when manipulating strings. PHP assumes all characters are eight bits (one byte), but because UTF-8 encoded characters can be longer, this can cause corruption of Unicode data. There is a PHP module, mbstring, which adds support for multi-byte character encodings; unfortunately, not all PHP systems have the mbstring module. In Joomla! we are provided with the static JString class; this class allows us to perform many of the normal string manipulation functions with UTF-8 characters. This example demonstrates how we can use JString to convert a string to upper case. Note that the method name is identical to the PHP function we would normally use: $string = JString::strtoupper($string); The following table describes the PHP string functions and the corresponding JString methods: PHP Function JString method Description strpos strpos Finds the rst occurrence of a string in a string. substr substr Gets a portion of a string. strtolower strtolower Converts a string to lowercase. strtoupper strtoupper Converts a string to uppercase. strlen strlen Counts the length of a string. str_ireplace str_ireplace Substitutes occurrences of a string with another string in a string (case insensitive). str_split str_split Splits a string into an array. strcasecmp strcasecmp Compares strings. strcspn strcspn Gets the length of the string before characters from the other parameters are found. stristr stristr Finds the rst occurrence of a string in a string (case insensitive). strrev strrev Reverses a string. strspn strspn Counts the longest segment of a string containing specied characters. substr_replace substr_replace Replaces a dened portion of a string. ltrim ltrim Removes white space from the left of a string. Getting Started [ 36 ] PHP Function JString method Description rtrim rtrim Removes white space from the right of a string. trim trim Removes white space from both ends of a string. ucfirst ucfirst Converts the rst character to uppercase. ucwords ucwords Converts the rst character of each word to uppercase. transcode Converts a string from one encoding to another. Requires the PHP iconv module. Coding Standards Using a standardized format makes code easier to read and allows other developers to edit code more easily. Joomla! uses the PEAR coding standards. A complete guide to the PEAR coding standards is available at http://pear.php.net/manual/en/ standards.php. Here is a break down of the more common rules: Indents are four spaces: { // four space before me! Control structures have one space between the name and rst parenthesis: if (true) { Use curly braces even when they are optional. Functions and methods are named using the camelCase standard with a lowercase rst character. Functions and method declarations have no spaces between the name and rst parenthesis. Parameter lists have no spaces at the ends. Parameters are separated by one space: foo($bar0, $bar1, $bar2); Optional function and method parameters must be at the end of the parameter list. Optional parameter values, signied by an equals sign, are separated by spaces: function foo($bar0, $bar1, $bar2 = '') Use phpDocumentor tags to comment code http://www.phpdoc.org/. Use include_once() and require_once() in preference to include() and require(). Use <?php ?> in preference to all other PHP code block delimiters. • • • • • • • • • Chapter 2 [ 37 ] phpDocumentor phpDocumentor is a documentation tool that allows us to easily create documentation from PHP source code. The documentation is extracted from the source and from special comments within the source; these comments are very similar to those used by JavaDoc. This example demonstrates how we might document a simple function: /** * Adds two integers together * * @param int $value1 Base value * @param int $value2 Value to add * @return int Resultant vaue */ function addition($value1, $value2) { return ((int)$value1 + (int)$value2) } The multiline comment denotes a DocBlock, notice that it uses a double asterisk at the start. The rst line is a general description of the function, this description can span more than one line. @param and @return are tags. The @param tag is used to dene a parameter in the format (the name is optional): @param type [$name] description The @return tag is used to dene the return value in the format: @return type description So our initial example is telling us that the addition() function has two integer parameters named that it will add togther and return the resultant integer value. When we document complex functions, we might want to provide two descriptions, a long description and a short description. This example demonstrates how we do this: /** * Does some complex processing * * A verbose description of the function that spans more than * one line * * @param int $value1 Base value Getting Started [ 38 ] * @param int $value2 Value to add * @return int Resultant vaue */ function someComplexFunction($value1, $value2) { // does some complex processing } Functions are not the only elements that can be documented. Elements that we can document include: class methods class varaibles classes dene() les function declarations global variables (requires use of the @global tag) include()/include_once() require()/require_once() This list denes some common tags we are likely to encounter: @access private|protected|public @author name @param type [$name] description @return type description @static The DocBlocks are easy to read when they are displayed in code, but, more importantly, we can automatically create documentation from the source code. For more information about using phpDocumentor please refer to http://www.phpdoc.org/. • • • • • • • • • • • • • • Chapter 2 [ 39 ] Summary The application embodies the complete process of responding to a request. The document is used to determine the format of the response data and as a buffer to store the response data. Instead of using the request and session hashes in Joomla!, we use the static JRequest class and the global JSession object. The JRoute class enables us to parse and build internal URIs. The JText class is used to translate strings into different languages. Limitations in PHP means we must use JString to handle UTF-8 data; if we do not we run the risk of corrupting data. Although the coding standards that we use are ultimately up to us, we should consider using the same standards as those implemented by the Joomla! project. If we chose not to use these standards, we should still consider adding doctags to our classes and functions because they can greatly decrease development and debug time. The Database This chapter details the role of the database in Joomla!. It denes some standard rules we need to abide by. It explains different ways in which we can query the database. It also briey covers the ADOdb emulation that is available for developers wanting to port existing applications. Joomla! is currently designed to use the MySQL database. However, the architecture does allow for the implementation of other database drivers. There is some uncertainty surrounding the issue of supporting other databases, because of the usage in queries of functions and syntax that are specic to MyS�L.of functions and syntax that are specic to MyS�L.that are specic to MyS�L. The Core Database Much of the data we see in Joomla! is stored in the database. A base installation has over thirty tables. Some of these are related to core extensions and others to the inner workings of Joomla!. There is an ofcial database schema, which describes the tables created during the installation. For more information, please refer to: http://dev.joomla.org/ component/option,com_jd-wiki/Itemid,31/id,guidelines:database/. A tabular description is available at: http://dev.joomla.org/downloads/ Joomla15_DB-Schema.htm. We access the Joomla! database using the global JDatabase object. The JDatabase class is an abstract class, which is extended by different database drivers. There are currently only two database drivers included in the Joomla! core, MySQL and MySQLi. We access the global JDatabase object using JFactory: $db =& JFactory::getDBO(); The Database [ 42 ] Extending the Database When we create extensions, we generally want to store data in some form. If we are using the database, it is important to extend it in the correct way. More information on extending the database with components is available in Chapter 4. Table Prefix All database tables have a prex, normally jos_, which helps in using a single database for multiple Joomla! installations. When we write SQL queries, to accommodate the variable table prex, we use a symbolic prex that is substituted with the actual prex at run time. Normally the symbolic prex is #__, but we can specify an alternative prex if we want to. Schema Conventions When we create tables for our extensions, we must follow some standard conventions. The most important of these is the name of the table. All tables must use the table prex and should start with name of the extension. If the table is storing a specic entity, add the plural of the entity name to the end of the table name separated by an underscore. For example, an items table for the extension 'My Extension' would be called #__myExtension_items. Table eld names should all be lowercase and use underscore word separators; you should avoid using underscores if they are not necessary. For example, you can name an email address eld as email. If you had a primary and a secondary email eld, you could call them email and email_secondary; there is no reason to name the primary email address email_primary. If you are using a primary key record ID, you should call the eld id, make it of type integer auto_increment, and disallow null. Doing this will allow you to use the Joomla! framework more effectively. Common Fields We may use some common elds in our tables. Using these elds will enable us to take advantage of the Joomla! framework. We will discuss how to implement and manipulate these elds, using the JTable class, later in this chapter. Chapter 3 [ 43 ] Publishing We use publishing to determine whether to display data. Joomla! uses a special eld called published, of type tinyint(1); 0 = not published, 1 = published. Hits If we want to keep track of the number of times a record has been viewed, we can use the special eld hits, of type integer and with the default value 0. Checking Out To prevent more than one user trying to edit one record at a time we can check out records (a form of software record locking). We use two elds to do this, checked_ out and checked_out_time. checked_out, of type integer, holds the ID of the user that has checked out the record. checked_out_time, of type datetime, holds the date and time when the record was checked out. A null date and a user ID of 0 is recorded if the record is not checked out. Ordering We often want to allow administrators the ability to choose the order in which items appear. The ordering eld, of type integer, can be used to number records sequentially to determine the order in which they are displayed. This eld does not need to be unique and can be used in conjunction with WHERE clauses to form ordering groups. Parameter Fields We use a parameter eld, a TEXT eld normally named params, to store additional information about records; this is often used to store data that determines how a record will be displayed. The data held in these elds is encoded as INI strings (which we handle using the JParameter class). Before using a parameter eld, we should carefully consider the data we intend to store in the eld. Data should only be stored in a parameter eld if all of the following criteria are true: Not used for sorting records Not used in searches Only exists for some records Not part of a database relationship • • • • The Database [ 44 ] Schema Example Imagine we have an extension called 'My Extension' and an entity called foobar. The name of the table is #__myextension_foobars. This schema describes the table: Field Datatype NOT NULL AUTO INC UNSIGNED DEFAULT id INTEGER NULL content TEXT checked_out INTEGER 0 checked_out_time DATETIME 0000-00-00 00:00:00 params TEXT ordering INTEGER 0 hits INTEGER 0 published TINYINT(1) 0 This table uses all of the common elds and uses an auto-incrementing primary key ID eld. When we come to dene our own tables we must ensure that we use the correct data types and NOT NULL, AUTO INC, UNSIGNED and DEFAULT values. The SQL displayed below will create the table described in the above schema: CREATE TABLE '#__myextension_foobars' ( 'id' INTEGER UNSIGNED NOT NULL DEFAULT NULL AUTO_INCREMENT, 'content' TEXT NOT NULL DEFAULT '', 'checked_out' INTEGER UNSIGNED NOT NULL DEFAULT 0, 'checked_out_time' DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', 'params' TEXT NOT NULL DEFAULT '', 'ordering' INTEGER UNSIGNED NOT NULL DEFAULT 0, 'hits' INTEGER UNSIGNED NOT NULL DEFAULT 0, 'published' INTEGER UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY('id') ) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'; Date Fields We regularly use datetime elds to record the date and time at which an action has taken place. When we use these elds, it is important that we are aware of the effect of time zones. All dates and times should be recorded in UTC+0 (GMT / Z). [...]... component The name will also be used in the form com_parsedname; this is done automatically by Joomla! For example, the name 'My Extension' will also be used in the format com_myextension Once you have built your XML manifest file, create a new archive, which can be ZIP, TAR, GZ, TGZ, GZIP, BZ2, TBZ2, or BZIP2, and add the XML manifest file to it If you install the archive as a component, you should get... while programming and it ensures that we use standardized methods to perform actions [ 63 ] Component Design This chapter explains the concepts behind building Joomla! components and shows you how to build your own components Components have two main elements, the frontend and the backend At the heart of Joomla! components lies the MVC (Model-View-Controller) framework There are many ways in which the... specifically interested in Joomla!' s MVC implementation Setting up a Sandbox When we start building a new component, it is imperative that we have a sandbox; somewhere we can test the code Ideally, we should have more than one system so we can test our components on different server setups The quick and easy way to set up a component sandbox is to create the component folders in the frontend and backend This... pass when creating the ��������������������������������������� JDate���������������������������������� object can be in the format UNIX timestamp, RFC 28 22 / 822 , or ISO 8601 A more complete description of JDate���� ��������� is available in Chapter 12 Summary We should now be able to ���������������������������������������������������� successfully ��������������������������������������� create new... prevents users from obtaining a directory listing This folder structure is not compulsory If we want to use the Joomla! MVC, help (preferences button), and JTable subclasses, we must use the models, views, help, and tables folders The MVC A single Joomla! extension often caters for several user types and several interfaces This diagram describes how two different users might access the same system: Without... file named after the entity and be located in the models folder Imagine we are creating a model for the component 'My Extension' and the entity data is called foobar The model class would be called MyextensionModelFoobar and it would be located in models/foobar.php All model classes extend the abstract JModel class This example shows a very basic implementation of the MyextensionModelFoobar class //... 'Children'); $join2 = array('idfield' => 'ichildid', 'name' => '# myextension_illegitimate_children', 'joinfield' => 'parent', 'label' => 'illegitimate Children'); $joins = array($join1, $join2); The names of primary keys and foreign keys in all of the tables must not be the same as the names of any other fields in any of the other tables Otherwise, the query will become ambiguous and the method will... those handy common fields we mentioned earlier and JTable provides us with some useful methods for dealing specifically with those fields Throughout the Common Fields examples $table refers to an instance of the TableFoobar class and $id refers to the ID of the record we are dealing with [ 58 ] Chapter 3 Publishing To publish and un-publish data we can use the publish() method This method publishes and. .. want to use the JTable class with, we must create a new subclass When creating JTable subclasses we must follow some specific conventions These conventions enable us to integrate our extensions into Joomla! and the Joomla! framework Assuming we are building a component, our JTable subclasses should be located in separate files in a folder called tables within the component's administrative root The class... primary key field id in # myextension_foobars In this example, we verify there are no dependent records in the # myextension_children table before deleting a record from # myextension_foobars $join1 = array('idfield' 'name' 'joinfield' 'label' => => => => 'childid', '# myextension_children', 'parent', 'Children'); [ 57 ] The Database $joins = array($join1); if ($table->canDelete($id, $joins)) { if . * @param int $value1 Base value * @param int $value2 Value to add * @return int Resultant vaue */ function addition($value1, $value2) { return ((int)$value1 + (int)$value2) } The multiline. iconv module. Coding Standards Using a standardized format makes code easier to read and allows other developers to edit code more easily. Joomla! uses the PEAR coding standards. A complete guide. implemented by the Joomla! project. If we chose not to use these standards, we should still consider adding doctags to our classes and functions because they can greatly decrease development and debug

Ngày đăng: 14/08/2014, 11:21

Mục lục

  • Mastering Joomla! 1.5 Extension and Framework Development

    • Chapter 2: Getting Started

      • Coding Standards

        • phpDocumentor

        • Summary

        • Chapter 3: The Database

          • The Core Database

          • Extending the Database

            • Table Prefix

            • Schema Conventions

              • Common Fields

              • Schema Example

              • Dealing with Multilingual requirements

              • Querying the Database

                • Writing Queries

                • Getting Results

                  • loadResult( ) : string

                  • loadResultArray( numinarray : int=0 ) : array

                  • loadAssoc( ) : array

                  • loadAssocList( key : string='' ) : array

                  • loadObject( ) : stdClass

                  • loadObjectList( key : string='' ) : array

                  • loadRow( ) : array

                  • loadRowList( key : int ) : array

                  • Using ADOdb

                  • JTable

                    • CRUD

                    • Manipulating Common Fields

                      • Publishing

                      • Hits

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan