Jump to content

Recommended Posts

I am a newbie

 

I am trying to build a CMS as described in a book. There are 5 files so far and I am sure I copied the code exactly from the book as is but I get the following error when I ru the script:
Fatal error: Class 'Page' not found in /var/www/html/kvcms/index.php on line 11

 

So there are the handler index.php

 

<?php

// { common variables and functions
include_once('vv.inc/common.inc');
$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '';
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
// }
// { get current page id
if (!$id) {
    if ($page) { // load by name
        $r = Page::getInstanceByName($page);
        if ($r && isset($r->id))
            $id = $r->id;
        unset($r);
    }
    if (!$id) { // else load by special
        $special = 1;
        if (!$page) {
            $r = Page::getInstanceBySpecial($special);
            if ($r && isset($r->id))
                $id = $r->id;
            unset($r);
        }
    }
}
// }
// { load page data
if ($id) {
    $PAGEDATA = (isset($r) && $r) ? $r : Page::getInstance($id);
} else {
    echo '404 thing goes here';
    exit;
}
// }
echo $PAGEDATA->body;

 

then you have the common include file that just calls the basics.php file and that is supposed to load the page.php file and reference the Page object. Which is clearly not happening. The book tells me that you can call and object (or load it) without including the file if you use an autoload function which is included here.

 

Where is the mistake please?

 

The basics.php file

 

<?php

session_start();
function _autoload($name) {
    require $name . '.php';
}

function dbInit() {
    if(isset($GLOBALS['db'])) return $GLOBALS['db'];
global $DBVARS;
$db = new PDO('mysql:host='. $DBVARS['hostname'] . '; dbname='. $DBVARS['db_name'].
        $DBVARS['username'], $DBVARS['password']);
$db->query('set name utf8');
$db->num_queries = 0;
$GLOBALS['db'] = $db;
return $db;
}
function dbQuery($query) {
    $db=dbinit();
    $q=$db->query($query);
    $db->num_queries++;
    return $q;
}
function dbRow($query) {
    $q = dbQuery($query);
    return $q->fetch(PDO::FETCH_ASSOC);
}
define('SCRIPTBASE', $_SERVER['DOCUMENT_ROOT'] . '/');
require SCRIPTBASE . '.private/config.php';
if(!defined('CONFIG_FILE'))
    define('CONFIG_FILE', SCRIPTBASE. '.private/config.php');
set_include_path(SCRIPTBASE. 'vv.php_classes' . PATH_SEPARATOR.get_include_path());

?>

 

the page.php file

 

<?php

class Page {

    static $instances = array();
    static $instancesByName = array();
    static $instancesBySpecial = array();

    function __construct($v, $byField = 0, $fromRow = 0, $pvq = 0) {
# byField: 0=ID; 1=Name; 3=special
        if (!$byField && is_numeric($v)) { // by ID
            $r = $fromRow ?
                    $fromRow :
                    ($v ?
                            dbRow("select * from pages where id=$v limit 1") :
                            array()
                    );
        } else if ($byField == 1) { // by name
            $name = strtolower(str_replace('-', '_', $v));
            $fname = 'page_by_name_' . md5($name);
            $r = dbRow("select * from pages where name like '"
                    . addslashes($name) . "' limit 1");
        } else if ($byField == 3 && is_numeric($v)) { // by special
            $fname = 'page_by_special_' . $v;
            $r = dbRow(
                    "select * from pages where special&$v limit 1");
        }
        else
            return false;
        if (!count($r || !is_array($r)))
            return false;
        if (!isset($r['id']))
            $r['id'] = 0;
        if (!isset($r['type']))
            $r['type'] = 0;
        if (!isset($r['special']))
            $r['special'] = 0;
        if (!isset($r['name']))
            $r['name'] = 'NO NAME SUPPLIED';
        foreach ($r as $k => $v)
            $this->{$k} = $v;
        $this->urlname = $r['name'];
        $this->dbVals = $r;
        self::$instances[$this->id] = & $this;
        self::$instancesByName[preg_replace(
                        '/[^a-z0-9]/', '-', strtolower($this->urlname)
                )] = & $this;
        self::$instancesBySpecial[$this->special] = & $this;
        if (!$this->vars)
            $this->vars = '{}';
        $this->vars = json_decode($this->vars);
    }

    function getInstance($id = 0, $fromRow = false, $pvq = false) {
        if (!is_numeric($id))
            return false;
        if (!@array_key_exists($id, self::$instances))
            self::$instances[$id] = new Page($id, 0, $fromRow, $pvq);
        return self::$instances[$id];
    }

    function getInstanceByName($name = '') {
        $name = strtolower($name);
        $nameIndex = preg_replace('#[^a-z0-9/]#', '-', $name);
        if (@array_key_exists($nameIndex, self::$instancesByName))
            return self::$instancesByName[$nameIndex];
        self::$instancesByName[$nameIndex] = new Page($name, 1);
        return self::$instancesByName[$nameIndex];
    }

    function getInstanceBySpecial($sp = 0) {
        if (!is_numeric($sp))
            return false;
        if (!@array_key_exists($sp, $instancesBySpecial))
            $instancesBySpecial[$sp] = new Page($sp, 3);
        return $instancesBySpecial[$sp];
    }

}

 

Any help is appreciated

 

 

Link to comment
https://forums.phpfreaks.com/topic/284543-calling-a-class/
Share on other sites

Copying from a book is risky. Replace your _autoload with

function autoload($name) {
    require strtolower($name) . '.php';
}
spl_autoload_register("autoload");
1a. The function is supposed to have two underscores, but the whole thing is outdated to begin with.

1b. Instead make a normal function and use spl_autoload_register

2. Unless the file is named "Page.php" (uppercase 'P') then you need strtolower() to lowercase the class name to get the filename.

Link to comment
https://forums.phpfreaks.com/topic/284543-calling-a-class/#findComment-1461312
Share on other sites

Thank you so much for the reply.

 

Yeah I know copying from a book is risky but how do I learn? And if you say outdated in what sense please? The book is not that old

I did what you said and now I get the following error which does not make sense:

 

Notice: Undefined index: password in /var/www/html/kvcms/ww.incs/basics.php on line 9

 

Is this index not defined in the file config.php?  which looks like this:

<?php

$DBVARS = array(
    'username' => 'cmsuser',
    'password ' => 'cmspass',
    'hostname' => 'localhost',
    'db_name' => 'cmsdb'
);

 

Your help is really appreciated. I want to learn this

Link to comment
https://forums.phpfreaks.com/topic/284543-calling-a-class/#findComment-1461314
Share on other sites

Yeah I know copying from a book is risky but how do I learn?

What I meant (which was entirely non-obvious, sorry) was that copying from a printed book means you have to type everything by hand. It's easy to make a typo.

See if the book has a website where you can download the files. Would also save you a lot of time.

 

And if you say outdated in what sense please? The book is not that old

How old is "that old"?

- The __autoload function has been deprecated for a while now, in favor of that spl_autoload_register() I mentioned

- Using __construct in the class is more recent, but there's no use of "accessibility modifiers": public, private, protected

 

It's also bad form to use @s everywhere like that code does, as well as the global keyword, but that goes more toward the quality of the material than its age.

 

I did what you said and now I get the following error which does not make sense...

It may very well be defined in that file, but that file needs to be required before it's available. And should be at the global scope - not inside a function or class. Which it looks like it is... except the line numbers don't match up? What's the current version of the file?
Link to comment
https://forums.phpfreaks.com/topic/284543-calling-a-class/#findComment-1461318
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.