3

これまで、私のウェブサイトはすべて非常に直線的なコードで書かれており (QBASIC に感謝します!)、コードが繰り返し、乱雑で、まとまりのないものであることにしばしば悩まされていました。すべての動的ページには常に独自の個別の .php ファイルがあり、関数を使用したことはありません。

テンプレート エンジンとして Smarty を使用して OOP を使用して、サイト全体を書き直しています。

これが私の現在のプロセスです:

1) index.php?/view/fluffybunny への訪問者のヒット。index.php は、Web サイトの残りの部分の単なるハンドラーです。

// main config holds all database, sphinx and memcached settings
// and also connects to server
require_once '../config/site.cfg.php';

$urlPath = explode('/',$_GET['path']);

$page = new page($tpl,$db);

if (!empty($urlPath[1]))
{
    switch ($urlPath[1])
    {
        case 'view': $page->view($urlPath); break;
        case 'browse': $page->browse($urlPath); break;
        case 'index': $page->index($urlPath); break;
        default: $page->index($urlPath); break;
    }
}
else
{
    header('HTTP/1.0 404 Not Found'); // then 404 because we dont want seo issues
    exit("File not found");
}

2) 'new page()' はオートローダーを起動して、page.class.php をインクルードします。

/* page Class
 * Created by James Napier 16/05/2013
 * Revision 0.1
 */
class page
{
    private $tpl;
    private $db;

    public function __construct($tpl='',$db='') {
        $this->tpl = $tpl;
        $this->db = $db;
    }   

    /*
    * Displays index page 
    * Depending on URL it either displays a local index or countrywide index
    */
    public function index($urlPath)
    {
        $locUrl = '';

        if (!empty($urlPath[3])) //this is the location part
        { 
            // init location class
            $location = new location($this->db);

            // check whether location exists
            if($location->checkByUrl($urlPath[3]))
            {
                $locUrl = '/in/'.$urlPath[3]; // if it does add location suffix to urls
            } 
            else
            { 
                // if it doesnt, 404 
                header('HTTP/1.0 404 Not Found');
                exit("File not found");
            }
        }

        // assign location url to template
        $this->tpl->assign('locUrl', $locUrl);

        // homepage breadcrumbs
        $this->tpl->assign('breadCrumbs',array(
            array('title'=>'Site '.COUNTRY_CODE1, 'friendlyurl'=>'/'),
            array('title'=>'Home', 'friendlyurl'=>'/')));   

        // Build the template and display it
        $this->tpl->display('index.tpl');
    }


    /*
    * Displays individual listing 
    * Uses the ID from the end of the URL to display the correct item 
    */  
    public function view($urlPath)
    {   
        $id = end($urlPath);

        if (!empty($id))
        {
            // Retrieve the article from the database along with POINT values
            $stmt = $this->db->prepare('SELECT *, X(locpoint) as x, Y(locpoint) as y FROM listing WHERE id = :id LIMIT 1');
            $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            $stmt->execute();

            if($listing = $stmt->fetch(PDO::FETCH_ASSOC))
            {
                // Deal with the article status
                if ($listing['status'] == 'deleted')
                {
                    $this->err404();
                }
                elseif ($listing['status'] == 'disabled')
                {
                    $this->tpl->assign('bannerErr','THIS AD HAS EXPIRED AND IS PENDING DELETION');
                }
                elseif ($listing['status'] == 'pending')
                {
                    $this->tpl->assign('bannerErr','THIS AD IS NOT YET ACTIVE AND IS BEING REVIEWED BY THE FLOGR TEAM');            
                }

                // Start building the basic page vars from the results
                $this->tpl->assign('itemID', $listing['id']);
                $this->tpl->assign('itemTitle',$listing['title']);
                $this->tpl->assign('itemDescription',$listing['description']);
                $this->tpl->assign('itemShortDesc',$listing['shortdesc']);

                // price
                $this->tpl->assign('itemPrice', number_format($listing['price']));
                $this->tpl->assign('itemPriceTag',$listing['pricetag']);

                // location details
                $this->tpl->assign('itemLatLng', $listing['x'].','.$listing['y']);
                $this->tpl->assign('itemLocation', $listing['loctext']);

                // contact details
                $this->tpl->assign('itemContactName',$listing['name']);
                $this->tpl->assign('itemContactNo', $listing['phone']);
                $this->tpl->assign('itemContactType', $listing['type']);

                // images
                $this->tpl->assign('itemImages', json_decode($listing['images'], true));


                // Retrieve the category info for breadcrumbs and titles
                $getContent = new getContent();

                // breadcrumbs
                $this->tpl->assign('breadCrumbs',$getContent->breadCrumbs($listing['catid'],'/browse/', $this->db));


                // Page and SEO titls
                $this->tpl->assign('headTitle',$listing['title'].' located in '.$listing['loctext'].' | site.com');
                $this->tpl->assign('headDesc', $listing['shortdesc']);

                // Build the template and display it
                $this->tpl->display('view_ad.tpl');

                // Update hits and set viewed session var
                $_SESSION['filter']['viewed'][] = $listing['id'];
                $stmt = $this->db->query('UPDATE LOW_PRIORITY listing SET hits = hits+1 WHERE id = '.$listing['id']);
            }
            else
            {
                $this->err404();
            }
        }
        else
        {
            $this->err404();
        }   
    }


    /*
    * standard 404 error 
    */  
    public function err404()
    {
        header('HTTP/1.0 404 Not Found');
        exit("File not found");
    }
}

最初に私の質問は、私が OOP の初心者として犯している明らかな間違いを誰かが見ることができますか?

次に、index.php ハンドラが $page->index()、$page->view() を呼び出したかどうかに関係なく、すべてのページ (ユーザー認証など) で実行する必要があるコードの大きなブロックがいくつかあります。 ..等。このコードを page.class.php に統合するにはどうすればよいですか?

4

1 に答える 1

0

あなたのコードに関する限り、OOP の実行はうまく行っていますが、フレームワークをゼロからプログラミングすることは、基本的に車輪の再発明です。CakePHP、Zend Framework、Laravel などの既存のフレームワークを使用することを強くお勧めします。フレームワークをしばらく使用すると、好きなものと嫌いなものを把握し始めます。その時点で、独自のフレームワークを作成することは良い練習になります。しかし、その時点でも、世の中のオープンソース フレームワークは、1,000 時間とは言わないまでも、100 時間の男性/女性時間を使用して開発されてきたことを認識する必要があります。フレームワークをゼロから構築するよりもはるかに簡単です。

于 2013-06-10T17:38:00.730 に答える