Actions

Difference between revisions of "How to create a stand-alone application using the Joomla! Platform"

From Joomla! Documentation

(Building a Web Application on the Platform)
 
(19 intermediate revisions by 6 users not shown)
Line 25: Line 25:
 
Tell the world that you just made your first successful Joomla Platform app by tweeting the following:  “OMG, I just wrote a #jplatform app! #joomla”
 
Tell the world that you just made your first successful Joomla Platform app by tweeting the following:  “OMG, I just wrote a #jplatform app! #joomla”
  
 +
'''Step 7:  Add to the collection'''
 +
 +
Add your application to the example collection at [http://joomlacode.org/gf/project/platformapps/ Platform Examples]
 
----
 
----
 +
Problems? Check [[Platform_Applications_Tips_and_Tricks | Platform Tips and Tricks]]
  
 +
== Examples ==
  
== Example 1: Hello World Command Line Interface (CLI) App ==
+
=== Example 1: Hello World Command Line Interface (CLI) App ===
  
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
define( '_JEXEC', 1 );
+
define('_JEXEC', 1);
 +
define('JPATH_BASE', dirname(__FILE__));
  
require_once ( '../libraries/import.php' );
+
require '../libraries/import.php';
jimport( 'joomla.application.cli' );
+
  
class HelloWorld extends JCli
+
class HelloWorld extends JApplicationCli
 
{
 
{
 
+
    public function execute()
public function execute( )
+
 
     {
 
     {
      $this->out( 'Hello World' );
+
        $this->out('Hello World');
 
     }
 
     }
 
}
 
}
  
JCli::getInstance( 'HelloWorld' )->execute( );
+
JApplicationCli::getInstance('HelloWorld')->execute();
 
</source>
 
</source>
  
 
+
=== Example 2: Drawing cool things in the Terminal Screen ===
== Example 2: Drawing cool things in the Terminal Screen ==
+
  
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
define( '_JEXEC', 1 );
+
define('_JEXEC', 1);
 
   
 
   
require_once ( '../libraries/import.php' );
+
require '../libraries/import.php';
jimport( 'joomla.application.cli' );
+
 
   
 
   
class JoomlaRocks extends JCli
+
class JoomlaRocks extends JApplicationCli
 
{
 
{
+
    public function execute()
public function execute( )
+
 
     {
 
     {
       $this->out( '  .          .    .__      |      | ' );
+
       $this->out('  .          .    .__      |      | ');
       $this->out( '  | _  _ ._ _ | _.  [__) _  _.|_/ __ | ' );
+
       $this->out('  | _  _ ._ _ | _.  [__) _  _.|_/ __ | ');
       $this->out( '\__|(_)(_)[ | )|(_]  |  \(_)(_.| \_)  * ' );
+
       $this->out('\__|(_)(_)[ | )|(_]  |  \(_)(_.| \_)  * ');
 
     }
 
     }
 
}
 
}
 
   
 
   
JCli::getInstance( 'JoomlaRocks' )->execute( );
+
JApplicationCli::getInstance('JoomlaRocks')->execute();
 
</source>
 
</source>
  
 
+
=== Example 3: Hello World using a var to save your name ===
== Example 3: Hello World using a var to save your name ==
+
  
 
<source lang="php">
 
<source lang="php">
Line 80: Line 80:
 
define('_JEXEC', 1);
 
define('_JEXEC', 1);
  
require_once '../libraries/import.php';
+
require '../libraries/import.php';
 
+
jimport('joomla.application.cli');
+
  
class HelloYou extends JCli
+
class HelloYou extends JApplicationCli
 
{
 
{
 
     public function execute()
 
     public function execute()
Line 108: Line 106:
 
}
 
}
  
JCli::getInstance('HelloYou')->execute();
+
JApplicationCli::getInstance('HelloYou')->execute();
 
</source>
 
</source>
  
 
+
=== Example 4: Get your recent Tweets ===
== Example 4: Get your recent Tweets ==
+
  
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
 
 
define('_JEXEC', 1);
 
define('_JEXEC', 1);
  
require_once '../libraries/import.php';
+
require '../libraries/import.php';
  
jimport('joomla.application.cli');
+
class TwitterFeed extends JApplicationCli
 
+
class TwitterFeed extends JCli
+
 
{
 
{
 +
    public function execute()
 +
    {
 +
        $this->out('What is your twitter handle?');
 +
        $username = $this->in();
  
//Get Latest Tweet
+
        $this->out('How many tweets to view?');
function latest_tweet( $username, $count = 5 )
+
        $count = $this->in();
{
+
    $url = "http://twitter.com/statuses/user_timeline/$username.xml?count=$count";
+
  
    $xml = simplexml_load_file( $url ) or die( "could not connect" );
+
        $tweets = $this->latest_tweet($username, $count);
 
+
        $this->out($tweets);
    $text = ''; 
+
    }
    foreach( $xml->status as $status )
+
    {
+
        $text .= $status->text . '
+
 
+
';
+
    }
+
  
    return $text;
+
    // Get Latest Tweet
}
+
    private function latest_tweet($username, $count = 5)
 
+
    {
 +
        $url = 'http://twitter.com/statuses/user_timeline/'.$username.'.xml?count='.$count;
  
public function execute()
+
        $xml = simplexml_load_file($url) or die('could not connect');
{
+
 
+
    $this->out( 'What is your twitter handle?' );
+
    $username = $this->in( );
+
 
+
    $this->out( 'How many tweets to view?' );
+
    $count = $this->in( );
+
 
+
    $tweet = $this->latest_tweet( $username, $count );
+
    $this->out( $tweet );
+
}
+
  
protected function fetchConfigurationData()
+
        $text = '';
{
+
       
    return array();
+
        foreach($xml->status as $status)
}
+
        {
 +
            $text .= $status->text."\n";
 +
        }
 +
 
 +
        return $text;
 +
    }
 
}
 
}
  
JCli::getInstance('TwitterFeed')->execute();
+
JApplicationCli::getInstance('TwitterFeed')->execute();
 
</source>
 
</source>
----
 
 
  
{{review}}
+
== Building a Web Application on the Platform ==
 +
 
 +
These instructions will allow you to create a minimal web application that does not use a database.
  
== Building a Wep Application on the Platform ==
+
Problems? Check [[Platform Applications Tips and Tricks|Platform Tips and Tricks]]
These instructions will allow you to create a minimal web application that does not use a database.
+
  
 
Download the latest version of the Joomla! platform from github.
 
Download the latest version of the Joomla! platform from github.
  
 +
Create an <tt>index.php</tt> file in the root with the following starting code:
  
*Create an '''index.php''' file in the root with the following starting code:
+
<source>
<source lang="php">
+
 
if (file_exists(dirname(__FILE__) . '/defines.php'))
+
define('_JEXEC', 1);
 +
 
 +
// Fix magic quotes.
 +
@ini_set('magic_quotes_runtime', 0);
 +
 
 +
// Maximise error reporting.
 +
@ini_set('zend.ze1_compatibility_mode', '0');
 +
error_reporting(E_ALL);
 +
ini_set('display_errors', 1);
 +
 
 +
/*
 +
* Ensure that required path constants are defined.
 +
*/
 +
if (!defined('JPATH_BASE'))
 
{
 
{
include_once dirname(__FILE__) . '/defines.php';
+
define('JPATH_BASE', realpath(__DIR__));
 
}
 
}
  
// Define some things. Doing it here instead of a file because this
+
define('JPATH_LIBRARIES', JPATH_BASE . '/libraries');
// is a super simple application.
+
define('JPATH_BASE', dirname(__FILE__));
+
define('JPATH_PLATFORM', JPATH_BASE . '/libraries');
+
define('JPATH_MYWEBAPP', JPATH_BASE);
+
  
//This actually means Joomla will look in the includes folder for the application.
+
/**
define('JPATH_MYWEBAPP', JPATH_BASE);
+
* Import the platform. This file is usually in JPATH_LIBRARIES
 +
*/
 +
require_once JPATH_LIBRARIES . '/import.legacy.php';
  
//When you want to switch to a folder uncomment this
+
/**
//require_once JPATH_BASE.'/includes/defines.php';
+
* Import the application.
 +
*/
 +
require_once JPATH_BASE.'/includes/application.php';
  
// Usually this will be in the framework.php file in the
 
// includes folder.
 
require_once JPATH_PLATFORM.'/import.php';
 
// Use jimport to get the specific packages your application needs.
 
jimport('joomla.environment.uri');
 
jimport('joomla.utilities.date');
 
//Uncomment this if you want to use a framework.php file instead.
 
//require_once JPATH_BASE.'/includes/framework.php';
 
 
//It's an application, so let's get the application helper.
 
jimport('joomla.application.helper');
 
$client = new stdClass;
 
$client->name = 'mywebapp';
 
$client->path = JPATH_MYWEBAPP;
 
 
JApplicationHelper::addClientInfo($client);
 
  
 
// Instantiate the application.
 
// Instantiate the application.
// We're setting session to false because we aren't using a database
+
$web = MyWebApp::getInstance('MyWebApp');
// so there is no where to store it.
+
$config = Array ('session'=>false);
+
  
$app = JFactory::getApplication('mywebapp', $config);
+
// Run the application
 
+
$web->execute();
// Render the application. This is just the name of a method you
+
// create in your application.php
+
$app->render();
+
  
 
</source>
 
</source>
  
Now create a '''application.php''' file.
+
Now create a folder <tt>includes</tt> in the root and inside it a file <tt>application.php</tt> with the following code:
 
+
<source>
<source lang="php">
+
 
/**
 
/**
  * @copyright  Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
+
  * Override the doExecute method from JApplicationWeb. Here you define what your application does.  
* @license GNU General Public License version 2 or later; see LICENSE.txt
+
 
  */
 
  */
 
+
class MyWebApp extends JApplicationWeb
// no direct access
+
defined('JPATH_PLATFORM') or die;
+
 
+
/**
+
* Joomla! Application class
+
*
+
* Provide many supporting API functions
+
*
+
* @package Joomla.MyWebApp
+
* @subpackage Application
+
*/
+
final class JMyWebApp extends JApplication
+
 
{
 
{
 
+
/**
/**
+
* Display the application.
* Display the application.
+
*/
*/
+
protected function doExecute(){
public function render()
+
{
+
$this->setBody(
echo '<h1>My Web Application</h1>';
+
'<h1>My Web Application</h1>'.
 
+
'The current URL is '.JUri::current().'<br/>'.
echo 'The current URL is '.JUri::current().'<br/>';
+
'The date is '. JFactory::getDate('now')
echo 'The date is '. JFactory::getDate('now');
+
                );
+
}
}  
+
 
}
 
}
 
 
</source>
 
</source>
  
The application.php file should go into the includes folder.
 
 
If you browse to the web page you should see the heading followed by the two sentences, including the url and the date.
 
If you browse to the web page you should see the heading followed by the two sentences, including the url and the date.
  
[[Category:Tips and tricks]]
+
[[Category:Platform]][[Category:Development]][[Category:Tutorials]]
[[Category:Development]]
+
 
+
== Use Existing Joomla Configuration in External PHP file ==
+
Sometimes you may need to write an external PHP file instead of working in Joomla files. Outside the Joomla Framework, we cannot use Joomla DB libraries, such as the Global object $db, loadResult(), loadResultArray, loadAssocList, loadRow() and so on.
+
In this case, we can use the '''custom PHP code''' plugin to write the code right in the Joomla content page. You can also include the Joomla configuration and write your own MySQL queries in external php file.
+
===Joomla Configuration===
+
If you open configuration.php, you will see that all variables inside are under the class '''JConfig()'''.
 In this example, I need the variables of $host, $db, $user and $password.
+
===Joomla Page===
+
Suppose we have a Joomla page called "jm_page.php". In jm_page.php, I tried to POST a request variable of $user_id from "jm_page.php" to the external PHP file called "external.php".
+
<source lang="php">
+
<form action="external.php" method="POST">

+
<input type="text" name="user_id" id="user_id" value="<?php echo $user_id; ?>" />

+
<input type="submit" />

+
</form>
+
</source>
+
===External Page===
+
In the code below, the objective is to use Jconfig Class without repeating the Database connection strings which were already defined in Joomla Configuration page.

 Having the DB established, we query and output the first value in the $result Array.

 In the Query, I tried to get the result of sex of the user based on the user id from the table "jos_community_user".
+
 
+
How to read $jconfig->host? 
$Jconfig is now the instance of the Jconfig class. host is the variable $host inside the class.
+
<source lang="php">
+
<?php
#### The following codes is written by Andy Ng
+
<http://www.pcinvent.net>
+
####
#### Please keep the above credit line to the Author ####


+
//get POST

+
$user_id = $_POST["user_id"];

+
echo $user_id;


+
//use joomla db class
+

require_once("configuration.php");

+
$jconfig = new JConfig();


+
//db establish

+
$db_error = "Sorry. We are maintaining the Website. Please try again later.";
+

$db_config = mysql_connect( $jconfig->host, $jconfig->user, $jconfig->password ) or die( $db_error );

+
mysql_select_db( $jconfig->db, $db_config ) or die( $db_error );


+
//db query result

+
$query = "SELECT user_sex FROM jos_community_user WHERE user_id = $user_id";
+
//get user_sex

+
$query_execute = mysql_query($query);

+
$result = mysql_fetch_row($query_execute);

+
echo $result[0];


+
mysql_close($db_config);//andy:close db for security reason

+
?>
+
</source>
+

Latest revision as of 05:04, 5 April 2012

Contents

How to Build Your First Joomla Platform Application

This article will allow you to create your first Joomla Platform application, following a step-by-step process outlined below. We’ll assume you’re in an environment that has access to PHP (Mac OS X has this by default), and that you’ve got a connection to the Internet to download the platform project.

Step 1: Download the latest Joomla Platform

Simply point your Web browser to http://github.com/joomla/joomla-platform and then click on the “Downloads” button. In the pop-up window that appears, click on either the “Download .tar.gz” button or the “Download .zip” button, depending on your preference.

Step 2: Extract the Joomla Platform in your own environment

After you’ve downloaded the file, extract it in the location of your choosing.

Step 3: Create a new file

Create a folder named ‘examples’ within the root directory where you extracted the Joomla Platform. Using your favorite text/code editor, copy/paste code from the following examples (one at a time) into a new file. (Name the file as: ‘helloworld.php‘ or other name that you prefer).

Step 4: Execute your application from the command line interface (CLI)

Using your favorite CLI (maybe Terminal on the Mac, or PuTTy on Windows), navigate to the ‘examples’ folder where you saved your file. Type “php helloword.php” (or whatever you named your file) and click the enter key on your keyboard.

Step 5: Read the result on your screen, savor the moment

Step 6: Tweet your success

Tell the world that you just made your first successful Joomla Platform app by tweeting the following: “OMG, I just wrote a #jplatform app! #joomla”

Step 7: Add to the collection

Add your application to the example collection at Platform Examples


Problems? Check Platform Tips and Tricks

Examples

Example 1: Hello World Command Line Interface (CLI) App

<?php
define('_JEXEC', 1);
define('JPATH_BASE', dirname(__FILE__));
 
require '../libraries/import.php';
 
class HelloWorld extends JApplicationCli
{
    public function execute()
    {
        $this->out('Hello World');
    }
}
 
JApplicationCli::getInstance('HelloWorld')->execute();

Example 2: Drawing cool things in the Terminal Screen

<?php
define('_JEXEC', 1);
 
require '../libraries/import.php';
 
class JoomlaRocks extends JApplicationCli
{
    public function execute()
    {
       $this->out('   .           .     .__       |      | ');
       $this->out('   | _  _ ._ _ | _.  [__) _  _.|_/ __ | ');
       $this->out('\__|(_)(_)[ | )|(_]  |  \(_)(_.| \_)  * ');
    }
}
 
JApplicationCli::getInstance('JoomlaRocks')->execute();

Example 3: Hello World using a var to save your name

<?php
define('_JEXEC', 1);
 
require '../libraries/import.php';
 
class HelloYou extends JApplicationCli
{
    public function execute()
    {
       $this->out('What is your name?');
       $name = $this->in();
 
       $this->out();
       $this->out('Hi '.$name.',');
       $this->out('Welcome to the Joomla Platform!');
       $this->out();
    }
 
    /**
    * We don’t really need configuration for this application.
    *
    * @return  void
    */
    protected function fetchConfigurationData()
    {
       return array();
    }
}
 
JApplicationCli::getInstance('HelloYou')->execute();

Example 4: Get your recent Tweets

<?php
define('_JEXEC', 1);
 
require '../libraries/import.php';
 
class TwitterFeed extends JApplicationCli
{
    public function execute()
    {
        $this->out('What is your twitter handle?');
        $username = $this->in();
 
        $this->out('How many tweets to view?');
        $count = $this->in();
 
        $tweets = $this->latest_tweet($username, $count);
        $this->out($tweets);
    }
 
    // Get Latest Tweet
    private function latest_tweet($username, $count = 5)
    {
        $url = 'http://twitter.com/statuses/user_timeline/'.$username.'.xml?count='.$count;
 
        $xml = simplexml_load_file($url) or die('could not connect');
 
        $text = '';
 
        foreach($xml->status as $status)
        {
            $text .= $status->text."\n";
        }
 
        return $text;
    }
}
 
JApplicationCli::getInstance('TwitterFeed')->execute();

Building a Web Application on the Platform

These instructions will allow you to create a minimal web application that does not use a database.

Problems? Check Platform Tips and Tricks

Download the latest version of the Joomla! platform from github.

Create an index.php file in the root with the following starting code:

define('_JEXEC', 1);
 
// Fix magic quotes.
@ini_set('magic_quotes_runtime', 0);
 
// Maximise error reporting.
@ini_set('zend.ze1_compatibility_mode', '0');
error_reporting(E_ALL);
ini_set('display_errors', 1);
 
/*
 * Ensure that required path constants are defined.
 */
if (!defined('JPATH_BASE'))
{
        define('JPATH_BASE', realpath(__DIR__));
}
 
define('JPATH_LIBRARIES',               JPATH_BASE . '/libraries');
 
/**
 * Import the platform. This file is usually in JPATH_LIBRARIES 
 */
require_once JPATH_LIBRARIES . '/import.legacy.php';
 
/**
 * Import the application.
 */
require_once JPATH_BASE.'/includes/application.php';
 
 
// Instantiate the application.
$web = MyWebApp::getInstance('MyWebApp');
 
// Run the application
$web->execute();

Now create a folder includes in the root and inside it a file application.php with the following code:

/**
 * Override the doExecute method from JApplicationWeb. Here you define what your application does. 
 */
class MyWebApp extends JApplicationWeb
{
                /**
                 * Display the application.
                 */
                protected function doExecute(){
 
                        $this->setBody(
                                '<h1>My Web Application</h1>'.
                                'The current URL is '.JUri::current().'<br/>'.
                                'The date is '. JFactory::getDate('now')
                        );
                }
}

If you browse to the web page you should see the heading followed by the two sentences, including the url and the date.