I want to be able to add many articles programmatically in Joomla, from the command line using the cli feature in Joomla CMS.
I am basically using Create a Joomla! Article Programmatically but my script closes out after creating just one article with the error line
Error displaying the error page: Application Instantiation
Error:Application Instantiation Error
This is the code that I am running from within the /cli folder in Joomla.
I am using Joomla 3.4
<?php
const _JEXEC = 1;
if (file_exists(dirname(__DIR__) . '/defines.php'))
{
require_once dirname(__DIR__) . '/defines.php';
}
if (!defined('_JDEFINES'))
{
define('JPATH_BASE', dirname(__DIR__));
require_once JPATH_BASE . '/includes/defines.php';
}
require_once JPATH_LIBRARIES . '/import.legacy.php';
require_once JPATH_LIBRARIES . '/cms.php';
require_once JPATH_CONFIGURATION . '/configuration.php';
class AddArticle extends JApplicationCli
{
public function doExecute()
{
$count = 10;
while ($count > 0)
{
$count--;
$jarticle = new stdClass();
$jarticle->title = 'New article added programmatically' . rand();
$jarticle->introtext = '<p>A programmatically created article</p>';
$table = JTable::getInstance('content', 'JTable');
$data = (array)$jarticle;
// Bind data
if (!$table->bind($data))
{
die('bind error');
return false;
}
// Check the data.
if (!$table->check())
{
die('check error');
return false;
}
// Store the data.
if (!$table->store())
{
die('store error');
return false;
}
}
}
}
JApplicationCli::getInstance('AddArticle')->execute();
I was able to find the answer to this as it had been raised as an issue at github, so I am posting that solution here.
https://github.com/joomla/joomla-cms/issues/7028
It is necessary to register the application like this, if the command line app uses JTable:
class MakeSql extends JApplicationCli
{
public function __construct()
{
parent::__construct();
JFactory::$application = $this; // this is necessary if using JTable
}
public function doExecute()
{
$db = JFactory::getDbo();
// ... etc etc ...
I did this and it worked fine.
Related
I'm working on a project whereby I have the following file structure:
index.php
|---lib
|--|lib|type|class_name.php
|--|lib|size|example_class.php
I'd like to auto load the classes, class_name and example_class (named the same as the PHP classes), so that in index.php the classes would already be instantiated so I could do:
$class_name->getPrivateParam('name');
I've had a look on the net but can't quite find the right answer - can anyone help me out?
EDIT
Thanks for the replies. Let me expand on my scenario. I'm trying to write a WordPress plugin that can be dropped into a project and additional functionality added by dropping a class into a folder 'functionality' for example, inside the plugin. There will never be 1000 classes, at a push maybe 10?
I could write a method to iterate through the folder structure of the 'lib' folder, including every class then assigning it to a variable (of the class name), but didn't think that was a very efficient way to do it but it perhaps seems that's the best way to achieve what I need?
Please, if you need to autoload classes - use the namespaces and class names conventions with SPL autoload, it will save your time for refactoring.
And of course, you will need to instantiate every class as an object.
Thank you.
Like in this thread:
PHP Autoloading in Namespaces
But if you want a complex workaround, please take a look at Symfony's autoload class:
https://github.com/symfony/ClassLoader/blob/master/ClassLoader.php
Or like this (I did it in one of my projects):
<?
spl_autoload_register(function($className)
{
$namespace=str_replace("\\","/",__NAMESPACE__);
$className=str_replace("\\","/",$className);
$class=CORE_PATH."/classes/".(empty($namespace)?"":$namespace."/")."{$className}.class.php";
include_once($class);
});
?>
and then you can instantiate your class like this:
<?
$example=new NS1\NS2\ExampleClass($exampleConstructParam);
?>
and this is your class (found in /NS1/NS2/ExampleClass.class.php):
<?
namespace NS1\NS2
{
class Symbols extends \DB\Table
{
public function __construct($param)
{
echo "hello!";
}
}
}
?>
If you have an access to the command line, you can try it with composer in the classMap section with something like this:
{
"autoload": {
"classmap": ["yourpath/", "anotherpath/"]
}
}
then you have a wordpress plugin to enable composer in the wordpress cli : http://wordpress.org/plugins/composer/
function __autoload($class_name) {
$class_name = strtolower($class_name);
$path = "{$class_name}.php";
if (file_exists($path)) {
require_once($path);
} else {
die("The file {$class_name}.php could not be found!");
}
}
UPDATE:
__autoload() is deprecated as of PHP 7.2
http://php.net/manual/de/function.spl-autoload-register.php
spl_autoload_register(function ($class) {
#require_once('lib/type/' . $class . '.php');
#require_once('lib/size/' . $class . '.php');
});
I have an example here that I use for autoloading and initiliazing.
Basically a better version of spl_autoload_register since it only tries to require the class file whenever you initializes the class.
Here it automatically gets every file inside your class folder, requires the files and initializes it. All you have to do, is name the class the same as the file.
index.php
<?php
require_once __DIR__ . '/app/autoload.php';
$loader = new Loader(false);
User::dump(['hello' => 'test']);
autoload.php
<?php
class Loader
{
public static $library;
protected static $classPath = __DIR__ . "/classes/";
protected static $interfacePath = __DIR__ . "/classes/interfaces/";
public function __construct($requireInterface = true)
{
if(!isset(static::$library)) {
// Get all files inside the class folder
foreach(array_map('basename', glob(static::$classPath . "*.php", GLOB_BRACE)) as $classExt) {
// Make sure the class is not already declared
if(!in_array($classExt, get_declared_classes())) {
// Get rid of php extension easily without pathinfo
$classNoExt = substr($classExt, 0, -4);
$file = static::$path . $classExt;
if($requireInterface) {
// Get interface file
$interface = static::$interfacePath . $classExt;
// Check if interface file exists
if(!file_exists($interface)) {
// Throw exception
die("Unable to load interface file: " . $interface);
}
// Require interface
require_once $interface;
//Check if interface is set
if(!interface_exists("Interface" . $classNoExt)) {
// Throw exception
die("Unable to find interface: " . $interface);
}
}
// Require class
require_once $file;
// Check if class file exists
if(class_exists($classNoExt)) {
// Set class // class.container.php
static::$library[$classNoExt] = new $classNoExt();
} else {
// Throw error
die("Unable to load class: " . $classNoExt);
}
}
}
}
}
/*public function get($class)
{
return (in_array($class, get_declared_classes()) ? static::$library[$class] : die("Class <b>{$class}</b> doesn't exist."));
}*/
}
You can easily manage with a bit of coding, to require classes in different folders too. Hopefully this can be of some use to you.
You can specify a namespaces-friendly autoloading using this autoloader.
<?php
spl_autoload_register(function($className) {
$file = __DIR__ . '\\' . $className . '.php';
$file = str_replace('\\', DIRECTORY_SEPARATOR, $file);
if (file_exists($file)) {
include $file;
}
});
Make sure that you specify the class file's location corretly.
Source
spl_autoload_register(function ($class_name) {
$iterator = new DirectoryIterator(dirname(__FILE__));
$files = $iterator->getPath()."/classes/".$class_name.".class.php";
if (file_exists($files)) {
include($files);
} else {
die("Warning:The file {$files}.class.php could not be found!");
}
});
do this in a file and called it anything like (mr_load.php)
this were u put all your classes
spl_autoload_register(function($class){
$path = '\Applicaton/classes/';
$extension = '.php';
$fileName = $path.$class.$extension;
include $_SERVER['DOCUMENT_ROOT'].$fileName;
})
;
then create another file and include mr_load.php; $load_class = new BusStop(); $load_class->method()
i'm watching a tutorials about CMS with OOP - PHP
i have error but to check it
i have to check ArticlesCatsModel.php first
on control page : (ArticlesCatsModel.php)
class ArticlesCatsModel
{
public function Get($extra='')
{
$cats = array();
System::Get('db')->Execute("SELECT * FROM `articles_cats` {$extra}");
if(System::Get('db')->AffectedRows()>0)
$cats = System::Get('db')->GetRows();
return $cats;
}
}
$m = new ArticlesCatsModel();
$m->Get();
?>
when i run it i get error
Fatal error: Class 'System' not found in /var/www/html/cms/includes/models/ArticlesCatsModel.php on line 11
globals.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('ROOT', dirname(__FILE__));
define('INC', ROOT.'/includes/');
define('CORE', INC.'/core/');
define('MODELS', INC.'/models/');
define('CONTROLLERS', INC.'/controllers/');
define('LIBS', INC.'/libs/');
/**
* Core Files
*/
require_once(CORE.'config.php');
require_once(CORE.'mysql.class.php');
require_once(CORE.'raintpl.class.php');
require_once(CORE.'system.php');
System::Store('db', new mysql());
System::Store('tpl', new RainTPL());
?>
Require the globals.php in your ArticlesCatsModel.php. So the System class can be used.
require_once('path/to/globals.php');
class ArticlesCatsModel
{
public function Get($extra='')
{
$cats = array();
System::Get('db')->Execute("SELECT * FROM `articles_cats` {$extra}");
if(System::Get('db')->AffectedRows()>0)
$cats = System::Get('db')->GetRows();
return $cats;
}
}
// why the lines below in the same file?
$m = new ArticlesCatsModel();
$m->Get();
I think class ArticlesCatsModel could not find globals.php
Make sure globals.php is included when ArticlesCatsModel class is called
I am writing a light weight php mvc framework for my portfolio and as a barebone setup for my future developments. I am stuck now because I am trying to use PSR-4 autoloader through composer. I understand the concept of PSR-4 etc but I am wondering how should I handle the routing.
My folder structure is:
--|-Root---
index.php
composer.json
-----|-application------
--------|-controller----
--------|-model---------
--------|-core----------
-----------|-baseController.php
-----------|-Application.php
-----------|-baseView.php
-----------|-baseModel.php
--------|-view----------
--------|-config
-----------|-config.php
-----|-vendor------
--------|-autoload.php
-----|-assets------
I am fairly good with php but writing an own mvc framework is a hard challange, even bigger because I never used PSR standards before.
Now my questions are:
Should I use router at all?
If yes then what pattern should I use to acomplish that.
So, in my index.php I define all constants to store directories like ROOT, APP, VENDOR. I then load vendor/autoload.php generated from my composer.json. After autoload.php I load and initiate my config by calling this code:
if(is_readable(APP . 'config/config.php'))
{
require APP . 'config/config.php';
//Initiate config
new AppWorld\Confyy\config();
}
else
{
throw new Exception('config.php file was not found in' . APP . 'config');
}
After config I setup application environment and then I initiate my app by calling:
// Start the application
new AppWorld\FrostHeart\Application();
Then my baseController is very very thin:
<?php
namespace AppWorld\FrostHeart;
use AppWorld\FrostHeart\baseView as View;
abstract class baseController {
public $currentView;
public function __construct() {
//Initiate new View object and set currentView to this object.
$this->currentView = new View();
}
}
And this is my baseView.php:
<?php
namespace AppWorld\FrostHeart;
class baseView {
public function show($file, $data = null, $showTemplate = 1) {
if($data != null) {
foreach($data as $key => $value) {
$this->{$key} = $value;
}
}
if($showTemplate === 1) {
require VIEW_DIR . header . ".php";
require VIEW_DIR . $file . ".php";
require VIEW_DIR . footer . ".php";
}
elseif($showTemplate === 0)
{
require VIEW_DIR . $file . ".php";
}
}
}
my config.php:
<?php
namespace AppWorld\Confyy;
class config {
public function __construct() {
$this->application();
$this->database();
}
public function application() {
/**
* Define application environment, defaults are:
*
* development
* live
*
*/
define("ENVIRONMENT", "development");
//Define base url
define("BASE_URL", "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
//Define default controller
define("DEFAULT_CONTROLLER", "landing");
//Define default method
define("DEFAULT_METHOD", "index");
//Define controllers directory
define("CONTROLLER_DIR", APP . "controller/");
//Define views directory
define("VIEW_DIR", APP . "view/");
}
public function database() {
//Define DB Server
define("DB_SERVER", "localhost");
//Define DB User
define("DB_USER", "root");
//Define DB Password
define("DB_PASSWORD", "");
//Define DB Name
define("DB_NAME", "test");
}
}
and at last my composer.json autoload section:
"autoload": {
"psr-4":{
"AppWorld\\": "application",
"AppWorld\\Conffy\\": "application/config",
"AppWorld\\FrostHeart\\": "application/core",
"AppWorld\\Controls\\": "application/controller"
}
}
So how should I implement a router that routes the URL requests and load correct files?
Thanks!
So with a little help I was able to get my first mvc framework up and running locally. Now that I've put it up on the server I'm not having any luck. I believe it's a configuration issue but I can't seem to figure it out.
Here's a Gif of what it should look like on the server but this is running it locally.
Why is nothing showing up when I go directly to the remote path? ie:
This does not work:
http://tomcat.cit.iupui.edu/alecory/Spring-2014/CIT-31300/Assignment%202/
Unless I set the 'URI' constant directly to '/register' which is it's output when running on localhost as seen in the notes below
This works but isn't what I want & doesn't include the header + footer:
http://tomcat.cit.iupui.edu/alecory/Spring-2014/CIT-31300/Assignment%202/views/register.php
config.php
<?php
include_once 'load.php';
// Local
// define ('URL_ROOT', 'http://localhost/');
// Remote
define ('URL_ROOT', 'http://tomcat.cit.ipui.edu/alecory/Spring-2014/Assignment%202/');
// define ('URI', $_SERVER['REQUEST_URI']);
// Outputs for:
// Local = /register
// Remote = /alecory/Spring-2014/CIT-31300/Assignment%202/views/register.php
define('URI', '/register'); // <= this is where I could set it myself and
# it would reroute the URL from
# /Assignment%202/views/register.php To
# /Assignment%202/
# (only showing /Assignment%202/ in the URL)
define ('DOC_ROOT', $_SERVER['DOCUMENT_ROOT']);
// Local = /Applications/MAMP/htdocs/CIT-31300/Assignment 2
// Remote = /var/www/
?>
controller.php
<?php
/**
* Controller
*
* Description: Basically tells the system what to do and in what order
*/
class Controller
{
public $load;
public $model;
function __construct()
{
// Make
$this->load = new Load();
$this->model = new Model();
// Set the $page = current view/page
$page = ltrim(URI, '/');
// Set default page to index
if (empty($page))
{
$page = 'index';
}
// Load the Pages
if (method_exists($this, $page))
{
// die(get_include_path());
require_once DOC_ROOT . '/views/inc/header.php';
$this->$page();
require_once DOC_ROOT . '/views/inc/footer.php';
}
else
{
require_once DOC_ROOT . '/views/inc/header.php';
$this->notFound();
require_once DOC_ROOT . '/views/inc/footer.php';
}
}
// Functions to load the various views
function index()
{
// $data = $this->model->my_user_info();
$this->load->view('myview.php', $data);
}
// function header()
// {
// $this->load->view('header.php', $data);
// }
// function footer()
// {
// $this->load->view('footer.php' $data);
// }
function login()
{
$this->load->view('login.php', $data);
}
function register()
{
$this->load->view('register.php', $data);
}
function notFound()
{
die('not found');
}
}
?>
I'm working on a project whereby I have the following file structure:
index.php
|---lib
|--|lib|type|class_name.php
|--|lib|size|example_class.php
I'd like to auto load the classes, class_name and example_class (named the same as the PHP classes), so that in index.php the classes would already be instantiated so I could do:
$class_name->getPrivateParam('name');
I've had a look on the net but can't quite find the right answer - can anyone help me out?
EDIT
Thanks for the replies. Let me expand on my scenario. I'm trying to write a WordPress plugin that can be dropped into a project and additional functionality added by dropping a class into a folder 'functionality' for example, inside the plugin. There will never be 1000 classes, at a push maybe 10?
I could write a method to iterate through the folder structure of the 'lib' folder, including every class then assigning it to a variable (of the class name), but didn't think that was a very efficient way to do it but it perhaps seems that's the best way to achieve what I need?
Please, if you need to autoload classes - use the namespaces and class names conventions with SPL autoload, it will save your time for refactoring.
And of course, you will need to instantiate every class as an object.
Thank you.
Like in this thread:
PHP Autoloading in Namespaces
But if you want a complex workaround, please take a look at Symfony's autoload class:
https://github.com/symfony/ClassLoader/blob/master/ClassLoader.php
Or like this (I did it in one of my projects):
<?
spl_autoload_register(function($className)
{
$namespace=str_replace("\\","/",__NAMESPACE__);
$className=str_replace("\\","/",$className);
$class=CORE_PATH."/classes/".(empty($namespace)?"":$namespace."/")."{$className}.class.php";
include_once($class);
});
?>
and then you can instantiate your class like this:
<?
$example=new NS1\NS2\ExampleClass($exampleConstructParam);
?>
and this is your class (found in /NS1/NS2/ExampleClass.class.php):
<?
namespace NS1\NS2
{
class Symbols extends \DB\Table
{
public function __construct($param)
{
echo "hello!";
}
}
}
?>
If you have an access to the command line, you can try it with composer in the classMap section with something like this:
{
"autoload": {
"classmap": ["yourpath/", "anotherpath/"]
}
}
then you have a wordpress plugin to enable composer in the wordpress cli : http://wordpress.org/plugins/composer/
function __autoload($class_name) {
$class_name = strtolower($class_name);
$path = "{$class_name}.php";
if (file_exists($path)) {
require_once($path);
} else {
die("The file {$class_name}.php could not be found!");
}
}
UPDATE:
__autoload() is deprecated as of PHP 7.2
http://php.net/manual/de/function.spl-autoload-register.php
spl_autoload_register(function ($class) {
#require_once('lib/type/' . $class . '.php');
#require_once('lib/size/' . $class . '.php');
});
I have an example here that I use for autoloading and initiliazing.
Basically a better version of spl_autoload_register since it only tries to require the class file whenever you initializes the class.
Here it automatically gets every file inside your class folder, requires the files and initializes it. All you have to do, is name the class the same as the file.
index.php
<?php
require_once __DIR__ . '/app/autoload.php';
$loader = new Loader(false);
User::dump(['hello' => 'test']);
autoload.php
<?php
class Loader
{
public static $library;
protected static $classPath = __DIR__ . "/classes/";
protected static $interfacePath = __DIR__ . "/classes/interfaces/";
public function __construct($requireInterface = true)
{
if(!isset(static::$library)) {
// Get all files inside the class folder
foreach(array_map('basename', glob(static::$classPath . "*.php", GLOB_BRACE)) as $classExt) {
// Make sure the class is not already declared
if(!in_array($classExt, get_declared_classes())) {
// Get rid of php extension easily without pathinfo
$classNoExt = substr($classExt, 0, -4);
$file = static::$path . $classExt;
if($requireInterface) {
// Get interface file
$interface = static::$interfacePath . $classExt;
// Check if interface file exists
if(!file_exists($interface)) {
// Throw exception
die("Unable to load interface file: " . $interface);
}
// Require interface
require_once $interface;
//Check if interface is set
if(!interface_exists("Interface" . $classNoExt)) {
// Throw exception
die("Unable to find interface: " . $interface);
}
}
// Require class
require_once $file;
// Check if class file exists
if(class_exists($classNoExt)) {
// Set class // class.container.php
static::$library[$classNoExt] = new $classNoExt();
} else {
// Throw error
die("Unable to load class: " . $classNoExt);
}
}
}
}
}
/*public function get($class)
{
return (in_array($class, get_declared_classes()) ? static::$library[$class] : die("Class <b>{$class}</b> doesn't exist."));
}*/
}
You can easily manage with a bit of coding, to require classes in different folders too. Hopefully this can be of some use to you.
You can specify a namespaces-friendly autoloading using this autoloader.
<?php
spl_autoload_register(function($className) {
$file = __DIR__ . '\\' . $className . '.php';
$file = str_replace('\\', DIRECTORY_SEPARATOR, $file);
if (file_exists($file)) {
include $file;
}
});
Make sure that you specify the class file's location corretly.
Source
spl_autoload_register(function ($class_name) {
$iterator = new DirectoryIterator(dirname(__FILE__));
$files = $iterator->getPath()."/classes/".$class_name.".class.php";
if (file_exists($files)) {
include($files);
} else {
die("Warning:The file {$files}.class.php could not be found!");
}
});
do this in a file and called it anything like (mr_load.php)
this were u put all your classes
spl_autoload_register(function($class){
$path = '\Applicaton/classes/';
$extension = '.php';
$fileName = $path.$class.$extension;
include $_SERVER['DOCUMENT_ROOT'].$fileName;
})
;
then create another file and include mr_load.php; $load_class = new BusStop(); $load_class->method()