суббота, 19 апреля 2008 г.

Строим свои хелперы

Строим свои хелперы


Создаем файл GlobalHelper.php в каталоге askeet/apps/frontend/lib/helper:


<?php



function pager_navigation($pager, $uri)

{

$navigation = '';



if ($pager->haveToPaginate())

{

$uri .= (preg_match('/\?/', $uri) ? '&' : '?').'page=';



// First and previous page

if ($pager->getPage() != 1)

{

$navigation .= link_to(image_tag('first.gif', 'align=absmiddle'), $uri.'1');

$navigation .= link_to(image_tag('previous.gif', 'align=absmiddle'), $uri.$pager->getPreviousPage()).'&nbsp;';

}



// Pages one by one

$links = array();

foreach ($pager->getLinks() as $page)

{

$links[] = link_to_unless($page == $pager->getPage(), $page, $uri.$page);

}

$navigation .= join('&nbsp;&nbsp;', $links);



// Next and last page

if ($pager->getPage() != $pager->getCurrentMaxLink())

{

$navigation .= '&nbsp;'.link_to(image_tag('next.gif', 'align=absmiddle'), $uri.$pager->getNextPage());

$navigation .= link_to(image_tag('last.gif', 'align=absmiddle'), $uri.$pager->getLastPage());

}



}



return $navigation;

}


Для использования этого хелпера в фрагменте шаблона question/templates/_list.php вызываем его так:


<?php use_helper('Text', 'Global') ?>



<?php foreach($question_pager->getResults() as $question): ?>

<div class="question">

<div class="interested_block">

<?php include_partial('interested_user', array('question' => $question)) ?>

</div>



<h2><?php echo link_to($question->getTitle(), 'question/show?stripped_title='.$question->getStrippedTitle()) ?></h2>



<div class="question_body">

<?php echo truncate_text($question->getBody(), 200) ?>

</div>

</div>

<?php endforeach; ?>



<div id="question_pager">

<?php echo pager_navigation($question_pager, 'question/list') ?>

</div>


Список часто задаваемых вопросов


В модуле question создаем новое действие:


public function executeRecent()

{

$this->question_pager = QuestionPeer::getRecentPager($this->getRequestParameter('page', 1));

}


Добавим в класс /lib/model/QuestionPeer.php:


public static function getRecentPager($page)

{

$pager = new sfPropelPager('Question', sfConfig::get('app_pager_homepage_max'));

$c = new Criteria();

$c->addDescendingOrderByColumn(self::CREATED_AT);

$pager->setCriteria($c);

$pager->setPage($page);

$pager->setPeerMethod('doSelectJoinUser');

$pager->init();



return $pager;

}


Шаблон /apps/frontend/module/question/templates/recentSuccess.php:


<h1>recent questions</h1>



<?php include_partial('list', array('question_pager' => $question_pager)) ?>


Добавим recent_questions правило в frontend/config/routing.yml :


recent_questions:
url: /question/recent/:page
param: { module: question, action: recent, page: 1 }

Меняем последнюю строку в recentSuccess.php на:


<?php include_partial('list', array('question_pager' => $question_pager, 'rule' => 'question/recent')) ?>


а также меняем последнюю строку в _list.php на fragment to:


<div id="question_pager">

<?php echo pager_navigation($question_pager, $rule) ?>

</div>


вызываем _list в modules/question/templates/listSuccess.php.


<h1>popular questions</h1>



<?php echo include_partial('list', array('question_pager' => $question_pager, 'rule' => 'question/list')) ?>


http://ваш хост/question/recent


Список частых ответов


Созаем модуль:


$ symfony init-module frontend answer


Создаем действие:


public function executeRecent()

{

$this->answer_pager = AnswerPeer::getRecentPager($this->getRequestParameter('page', 1));

}


Добавим в классAnswerPeer:


public static function getRecentPager($page)

{

$pager = new sfPropelPager('Answer', sfConfig::get('app_pager_homepage_max'));

$c = new Criteria();

$c->addDescendingOrderByColumn(self::CREATED_AT);

$pager->setCriteria($c);

$pager->setPage($page);

$pager->setPeerMethod('doSelectJoinUser');

$pager->init();



return $pager;

}


Шаблон recentSuccess.php:


<?php use_helper('Date', 'Global') ?>



<h1>recent answers</h1>



<div id="answers">

<?php foreach ($answer_pager->getResults() as $answer): ?>

<div class="answer">

<h2><?php echo link_to($answer->getQuestion()->getTitle(), 'question/show?stripped_title='.$answer->getQuestion()->getStrippedTitle()) ?></h2>

<?php echo count($answer->getRelevancys()) ?> points

posted by <?php echo link_to($answer->getUser(), 'user/show?id='.$answer->getUser()->getId()) ?>

on <?php echo format_date($answer->getCreatedAt(), 'p') ?>

<div>

<?php echo $answer->getBody() ?>

</div>

</div>

<?php endforeach ?>

</div>



<div id="question_pager">

<?php echo pager_navigation($answer_pager, 'answer/recent') ?>

</div>



Профиль пользователя


Для модуля user/show создаем действие


public function executeShow()

{

$this->subscriber = UserPeer::retrieveByPk($this->getRequestParameter('id', $this->getUser()->getSubscriberId()));

$this->forward404Unless($this->subscriber);



$this->interests = $this->subscriber->getInterestsJoinQuestion();

$this->answers = $this->subscriber->getAnswersJoinQuestion();

$this->questions = $this->subscriber->getQuestions();

}


Шаблон /apps/frontend/modules/user/templates/showSuccess.php:


<h1><?php echo $subscriber ?>�s profile</h1>



<h2>Interests</h2>



<ul>

<?php foreach ($interests as $interest): $question = $interest->getQuestion() ?>

<li><?php echo link_to($question->getTitle(), 'question/show?stripped_title='.$question->getStrippedTitle()) ?></li>

<?php endforeach; ?>

</ul>



<h2>Contributions</h2>



<ul>

<?php foreach ($answers as $answer): $question = $answer->getQuestion() ?>

<li>

<?php echo link_to($question->getTitle(), 'question/show?stripped_title='.$question->getStrippedTitle()) ?><br />

<?php echo $answer->getBody() ?>

</li>

<?php endforeach; ?>

</ul>



<h2>Questions</h2>



<ul>

<?php foreach ($questions as $question): ?>

<li><?php echo link_to($question->getTitle(), 'question/show?stripped_title='.$question->getStrippedTitle()) ?></li>

<?php endforeach; ?>

</ul>


Добавим следующие строки в question/templates/showSuccess.php и question/templates/_list.php вначале question_body div:


<div>asked by <?php echo link_to($question->getUser(), 'user/show?id='.$question->getUser()->getId()) ?> on <?php echo format_date($question->getCreatedAt(), 'f') ?></div>


Определим Date helper в _list.php.


Добавим навигационный бар


Меняем layout .


/apps/frontend/templates/layout.php


<div id="content_bar">

<?php include_component_slot('sidebar') ?>

<div class="verticalalign"></div>

</div>


view.yml:


default:
components:
sidebar: [sidebar, default]

$ symfony init-module frontend sidebar


apps/frontend/modules/sidebar/actions/ переимменуем actions.class.php в components.class.php и изменим содержимоена:


<?php



class sidebarComponents extends sfComponents

{

public function executeDefault()

{

}

}


Создадим /apps/frontend/modules/sidebar/templates/_default.php :


<?php echo link_to('ask a new question', 'question/add') ?>



<ul>

<li><?php echo link_to('popular questions', 'question/list') ?></li>

<li><?php echo link_to('latest questions', 'question/recent') ?></li>

<li><?php echo link_to('latest answers', 'answer/recent') ?></li>

</ul>


$ symfony clear-cache


view.yml :


default:
http_metas:
content-type: text/html; charset=utf-8

 metas:
title: symfony project
robots: index, follow
description: symfony project
keywords: symfony, project
language: en

 stylesheets:    [main, layout]

 javascripts:    []

 has_layout:     on
layout: layout

 components:
sidebar: [sidebar, default]

Меняем:


 metas:
title: askeet! ask questions, find answers
robots: index, follow
description: askeet!, a symfony project built in 24 hours
keywords: symfony, project, askeet, php5, question, answer
language: en

 

Комментариев нет: