class not found-OOP - php

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

Related

Programmatically add a Joomla Article from CLI

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.

How to use function in Class in PHP file

I'm developing a website for my project.
My folder structure looks like this:
/testingSite
/src
/WordBreaker.php
/index.php
I have a problem when using a function in WordBreaker.php
Here is how the function is defined in WordBreaker.php
<?php
class WordBreaker
{
function breakIntoWords($text)
{
$ranges = $this->breakIntoRanges($text);
$textList = $this->rangesToTextList($text, $ranges);
return $textList;
}
}
?>
And here is where I want to use a function (in index.php)
<?php
include "src/WordBreaker.php";
$instance = new WordBreaker ();
if ( isset( $_POST['btnSubmit'] ) ) {
$result = $instance->breakIntoWords($input);
}
?>
When I test the site, the error occur
Fatal error: Class 'WordBreaker' not found in C:\xampp\htdocs\testingSite\index.php on line 4
What should I do?
Use require_once instead of include
<?php
require_once("src/WordBreaker.php");
$instance = new WordBreaker ();
if ( isset( $_POST['btnSubmit'] ) ) {
$result = $instance->breakIntoWords($input);
}
?>
or you can add an autoloader function
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$vars = new IUarts();
print($vars->data);
?>
You can include it using DIR
require __DIR__."/src/WordBreaker.php";
$instance = new WordBreaker();
_ DIR _ is 'magical' and returns the directory of the current file without the trailing slash.
" If used inside an include, the directory of the included file is returned. This is equivalent to dirname(_ FILE _). This directory name does not have a trailing slash unless it is the root directory."

PHP: Load a class in a class

I have a class which is meant to "load" an another class, however I haven't been able to get it to work.
Error Message
Fatal error: Call to undefined method stdClass::echoString() in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\classes\example.php on line 5
Code
My code is broken up into three main sections:
api.php - the class to load the other classes.
API/exampleExternalAPI.php - (multiple files) the classes that api.php loads
example.php - the file that uses the main class (api.php)
If it helps these files can be downloaded from my dropbox
api.php
<?php
/* Config */
define('pathToAPIs','API/');
/* Autoload Function */
spl_autoload_register(function($className){
$namespace=str_replace("\\","/",__NAMESPACE__);
$className=str_replace("\\","/",$className);
$class=pathToAPIs.(empty($namespace)?"":$namespace."/")."{$className}.php";
include_once($class);
});
class api {
private $listOfAPIs;
public $APIs;
public function __construct($setAPI = null){
$this->updateListOfAPIs();
if (isset($setAPI)){
return $this->setAPI($setAPI);
}
}
public function setAPIs($setAPIs){
$this->APIs = null; // clears a previous call to this method
if (!is_array($setAPIs)){ // if not an array
$setAPIs = array($setAPIs); // make array
}
foreach ($setAPIs as $setAPIType){
if(in_array($setAPIType,$this->listOfAPIs)){
$array[$setAPIType] = new $setAPIType;
}
}
$this->APIs = json_decode(json_encode($array), FALSE); // convert array of required api objects to an object
return $this->APIs;
}
public function getListOfAPIs($update = false){
if ($update){
$this->updateListOfAPIs();
}
return $this->listOfAPIs;
}
private function updateListOfAPIs(){
$this->listOfAPIs = null; // clears a previous call to this method
$it = new FilesystemIterator(pathToAPIs);
foreach ($it as $fileinfo){
$filename = pathinfo($fileinfo->getFilename(), PATHINFO_FILENAME); // removes extension
$this->listOfAPIs[]= $filename;
}
}
public function __call($method,$args){
}
}
API/exampleExternalAPI.php
<?php
class exampleExternalAPI {
public function echoString($string){
echo $string;
}
}
example.php
<?php
require_once 'api.php';
$api = new api();
$api->setAPIs('exampleExternalAPI');
$api->APIs->exampleExternalAPI->echoString('string');
Background Info
(may give some insight to my madness)
I'm working on a project where I need to connect to lots of external APIs.
So I decided to creating a class to look after all my communications with external APIs ( not sure if best way - new to Object Oriented Programming).
I'm not entirely sure what problem you're trying to solve, but if your APIs is a simple stdClass instance it should work as expected:
public function setAPIs($setAPIs)
{
$this->APIs = new stdClass; // clears a previous call to this method
if (!is_array($setAPIs)) { // if not an array
$setAPIs = array($setAPIs); // make array
}
foreach ($setAPIs as $setAPIType) {
if (in_array($setAPIType, $this->listOfAPIs)) {
$this->APIs->{$setAPIType} = new $setAPIType;
}
}
return $this->APIs;
}

Using the factory method pattern: How do i instantiate new page from existing page

this is my index.php source, when i run it instantiate the home.php object. So index will always by default display the contents of home.php which is exactly what i want. When i click on the Features hyperlink it directs me to the features.php page but no content which is understandable because the features object has not been instantiated hence no output. If i do instantiate the features object then i get the contents of features.php and home.php on the index.php page which i do not want. How do i approach this, i have tried instantiating the needed object with if($_SERVER['REQUEST_METHOD'] == $_GET logic but no success. To sum it up: when i click the Features link the Features object should be instantiated and the url should reflect it eg. test/features.php instead of test/index.php.
<?php
include_once 'pagefactory.php';
include_once 'home.php';
include_once 'features.php';
include_once 'contact.php';
/**
* Class to instantiate the needed page objects
*/
class Client {
private $page_factory;
function __construct($webpage) {
$this->page_factory = new PageFactory;
echo $this->page_factory->startFactory(new $webpage);
}
}
$worker = new Client('home');
?>
ive figured it out by doing the following:
<?php
include_once 'pagefactory.php';
function __autoload($class_name) {
include $class_name . '.php';
}
/**
* Class to instantiate the needed page objects
*/
class Client {
private $page_factory;
function __construct($webpage) {
$this->page_factory = new PageFactory;
echo $this->page_factory->startFactory(new $webpage);
}
}
if (isset($_GET['features'])) {
$new_page = 'features';
$worker = new Client($new_page);
}elseif (isset($_GET['contact'])) {
$new_page = 'contact';
$worker = new Client($new_page);
} else {
$new_page = 'home';
$worker = new Client($new_page);
}
?>
Ive also updated my HTML links to :
<li>Home</li>
<li>Features</li>
<li>Contact</li>
It worked perfect for me, any suggestions in any alternative methods? If so SHARE

Get correct url / page to load in simple MVC

I´m making a "very" simple MVC framework in order to learn, however I have trouble getting other pages than the index page to show. In views folder I have 2 files one index.php and one register.php that I´m trying on.
I have tried various ways but can´t get my head around it. I know it is probably best to put different controller classes in different files and maybe a loader controller page but I´m a beginner with php so would like to make it as simple as possible for me...
Any help appriciated!
I have a index.php as a landing file in the root folder to bind everything together:
<?php
/* index.php
*
*/
require_once 'model/load.php';
require_once 'controller/main.php';
new mainController();
In the controller folder i have a file called main.php:
<?php
/* controller/main.php
*
*/
class mainController
{
public $load;
public function __construct()
{
$urlValues = $_SERVER['REQUEST_URI'];
$this->urlValues = $_GET;
//index page
if ($this->urlValues['controller'] == "") {
$indexPage = array("key" => "Hello");
$this->load = new load();
$this->load->view('index.php', $indexPage);
}
//register page
if ($this->urlValues['controller'] == "register.php") {
$registerPage = array("key" => "Register");
$this->load = new load();
$this->load->view('register.php', $registerPage);
}
}
}
And then I have a file called load.php in the model folder:
<?php
/* model/load.php
*
*/
class load
{
/* This function takes parameter
* $file_name and match with file in views.
*/
function view($file_name, $data = null)
{
if (is_readable('views/' . $file_name)) {
if (is_array($data)) {
extract($data);
}
require 'views/' . $file_name;
} else {
echo $this->file;
die ('404 Not Found');
}
}
}
In your mainController class you don't have property with the name urlValues, but you use it: $this->urlValues = $_GET;. And what is more you have local variable with the same name, that you don't use: $urlValues = $_SERVER['REQUEST_URI'];
And how you URL for register.php looks like?

Categories