Как сделать свой собственный Loop, как Wordpress Loop? - PullRequest
2 голосов
/ 04 октября 2009

Я новичок здесь и новый в PHP тоже ..

Просто интересно, как сделать свой собственный гибкий цикл, как в Wordpress ... Заметьте, я не говорю о WordPress .. Я хочу реализовать это на моем собственном PHP-приложении ...

давайте посмотрим назад в WP, есть код, похожий на этот:

while (have_post() : thepost())// .. bla bla...

echo the_title();
echo the_content();

endwhile; // this is just an ilustration

Не могли бы вы выяснить, как have_post () или the_post () взаимодействуют с базой данных, чтобы их можно было зациклить ..

спасибо ..

Ответы [ 4 ]

8 голосов
/ 05 октября 2009

WordPress использует глобальные переменные, которые эти функции изменяют при итерации цикла. e.g.:

var $posts = null;
var $post = null;
var $post_count = 0;
var $post_index = 0;

function have_post() {
    global $posts, $post_count, $post_index;

    $post_index = 0;

    // do a database call to retrieve the posts.
    $posts = mysql_query('select * from posts where ...');

    if ($posts) {
        $post_count = count($posts);
        return true;
    } else {
        $post_count = 0;
        return false;
    }
}

function thepost() {
    global $posts, $post, $post_count, $post_index;

    // make sure all the posts haven't already been looped through
    if ($post_index > $post_count) {
        return false;
    }

    // retrieve the post data for the current index
    $post = $posts[$post_index];

    // increment the index for the next time this method is called
    $post_index++;

    return $post;
}

function the_title() {
    global $post;
    return $post['title'];
}

function the_content() {
    global $post;
    return $post['content'];
}

Я бы определенно рекомендовал использовать кодирование в стиле ООП вместо того, что делает WordPress. Это сохранит переменные, определенные в экземпляре объекта, а не будет глобально доступным. e.g.:

class Post {
    function __construct($title, $content) {
        $this->title = $title;
        $this->content = $content;
    }

    function getTitle() {
        return $title;
    }

    function getContent() {
        return $content;
    }
}

class Posts {
    var $postCount = 0;
    var $posts = null;

    function __construct($conditions) {
        $rs = mysql_query('select * from posts where $conditions...');

        if ($rs) {
            $this->postCount = count($rs);
            $this->posts = array();

            foreach ($rs as $row) {
                $this->posts[] = new Post($row['title'], $row['content']);
            }
        }
    }

    function getPostCount() {
        return $this->postCount;
    }

    function getPost($index) {
        return $this->posts[$index];
    }
}
3 голосов
/ 04 октября 2009

Вы можете реализовать интерфейс Iterator .

1 голос
/ 16 апреля 2015

идея состоит в том, чтобы использовать глобальные переменные области видимости, а затем функции изменят эти переменные:

// first define the global variables:
$post_index = 0;
$posts_count = 0;
$post = null;
$posts = null;
$connection = null;

$connection = new PDO('mysql:host=127.0.0.1;dbname=YOUR_DB', 'YOUR_DB_USERNAME', 'YOUR_DB_USER_PASSWORD', array(PDO::ATTR_FETCH_MODE => PDO::FETCH_ASSOC));

$query = $connection->query('SELECT * FROM posts');
$posts = $query->fetchAll();

$posts_count = count($posts); // or = $query->rowCount()

// now you create the functions that will deal with and change those variables

function have_posts()
{
    global $post_index, $posts_count, $posts, $post;
    // if posts found and if post_index < posts_count return true else return false
    if($posts && $post_index < $post_count)
        return true;

    else
        return false;
}

function the_post()
{
    global $post_count, $post_index, $posts, $post;

    if($post_index > $post_count)
        return false;
    // fetch the post of the current index
    $post = $posts[$post_index];

    // increment the $post_index so that the next call to this function grapes the next post
    $post_index++;
}

function get_ID()
{
    global $post;
    return $post['ID'];
}


function get_title()
{
    global $post;
    return $post['title'];
}

Я надеюсь, что помощь.

0 голосов
/ 26 февраля 2010

Снова перейдите к этой проблеме: D

наконец я нашел решение,

@ Мэтт Хаггинс, я сделал несколько изменений в вашем коде, и теперь это работа ...

$posts = $wpdb->get_results('SELECT * FROM my_table',OBJECT);
$post = null;
$post_count = 0;
$post_index = 0;

function have_post() {
    global $posts, $post_count, $post_index;

    if ($posts && ($post_index <= $post_count)){
        $post_count = count($posts);
        return true;
    }
    else {
        $post_count = 0;
        return false;
    }
}

function the_post() {
    global $posts, $post, $post_count, $post_index;

    // make sure all the posts haven't already been looped through
    if ($post_index > $post_count) {
        return false;
    }

    // retrieve the post data for the current index
    $post = $posts[$post_index+1];

    // increment the index for the next time this method is called
    $post_index++;
    return $post;

}

function the_title() {
    global $post;
    return $post->Title;
}

function the_content() {
    global $post;
    return $post->Content;
}

//and the output

if(have_post()) : while(have_post()) : the_post();
echo '<h2>'.the_title().'</h2>';
echo '<p>'.the_content().'</p>';
endwhile; endif;

Большое спасибо ...:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...