View

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

License

joshuauyi/view

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A View class for php views. It includes the core features of a conventional view library, but is light weight and uses pure php syntax, no compiling and no need to learn a new syntax.

Download and unzip in your project directory.

Or install into a composer project using

composer require lydore/view

 require_once 'path/to/View.php'; // Set directory containing all views View::setBaseDir('path/to/views/dir');

All view files should be saved as file-name.view.php in the base view directory e.g homepage.view.php A view can contain regular html

DOCTYPE html>    

Hello World

In addition, views can have sections, vars and can be extended or yielded. The following example shows this functionality.

template.view.php is a master template view which home.view.php and about.view.php extend to use as their layout

DOCTYPE html>   View::get('page_title') ?>title> head> body>  View::yield('content') ?> body> html>
 View::set('page_title', 'View Home') ?>  View::section('content') ?> h1>Hello Worldh1> p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.p>  View::endsection() ?>  View::extend('template') ?>
 View::set('page_title', 'About View') ?>  View::section('content') ?> h1>About Ush1> p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.p>  View::endsection() ?>  View::extend('template') ?>

Now the view has been defined, next is to call the view from our code. To do that, use:

Variables can also be passed to the view by passing an associative array to the view method

 $name = 'John Doe'; View::render('home', ['name' => $name]); // OR use the compact method View::render('home', compact('name'));

Views can be included in other views by using the include method in the view

You may need a particluar set of data to be available to a view anytime the view is called, this can be done with the bindData method, however the method call needs to be placed such that it runs before the view is requested.

 View::bindData('home', function ()< // compact method can also be used $name = 'Jane Doe'; return [ 'site_name' => 'My site', 'body' => 'Cotent in my site body', 'name' => $name ]; >);

In the above example, the variables $site_name, $body and $name would always be available in the home.view.php file

It is possible to place views in sub directories of the view base directory, for instance if there is a directory layouts in the base directory and it has a view master.view.php, it can be accessed this way

To prevent html injection, values to be displayed in the view can be escaped using the e method

Источник

Разработка класса View в своем MVC фреймворке

Сейчас мы с вами сделаем класс View , который будет заниматься представлением данных. Он будет получать параметром объект класса Page , а своим результатом возвращать готовый HTML код страницы, который можно будет выводить на экран.

Посмотрим, как мы будем использовать класс View в файле index.php :

); $routes = require $_SERVER[‘DOCUMENT_ROOT’] . ‘/project/config/routes.php’; $track = ( new Router($routes) ) -> getTrack($_SERVER[‘REQUEST_URI’]); $page = ( new Dispatcher ) -> getPage($track); echo (new View) -> render($page); // вот так используем класс View ?>

Структура кода класса View будет иметь следующий вид:

renderLayout($page, $this->renderView($page)); > private function renderLayout(Page $page, $content) < >private function renderView(Page $page) < >> ?>

Метод renderView

Метод renderView будет получать файл представления и подставлять в него значения переменных. Это делается хитрым образом. Как вы знаете, переменные, которые используются в файле с представлением, содержатся в свойстве data объекта класса Page .

Эти переменные представляют собой ассоциативный массив. Нам нужно превратить этот массив в настоящие переменные, а затем подключить файл с представлением через include . В этом случае указанные доступные в этом файле переменные получат свое значение и на выходе мы получим просто HTML код уже с подставленными значениями переменных.

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

Метод renderLayout

Давайте теперь сделаем метод renderLayout . Этот метод будет брать файл лэйаута и подставлять в него значение переменных $title и $content (она будет передаваться параметром метода и будет представлять собой результат работы метода renderView ):

Итоговый код

Давайте соберем весь наш код вместе:

Разберите приведенный код класса View . Затем самостоятельно, не подсматривая в мой код, реализуйте такой же класс. Проверьте его работу.

Источник

Представление (Вид)

Последний этап формирования нашей страницы — это ее визуализация .

На данный момент у нас есть контроллер ( NewsController.php ), в котором уже есть нужные данные для формировании страницы.

Таблица news базы данных test2 :

MVC-5-1

Смысл использования представления на практике состоит в том, чтоб отделить весь HTML-код и положить его в отдельный файл.

Создадим html-файл и назовем его — index.php и положим в папку: views/news/index.php .

Он будет соответствовать для экшена actionIndex() (Список новостей) из NewsController.

Аналогично, в этой папке создадим файл view.php — для экшена actionView($id) (Просмотр одной новости).

В папке tamplate разместим файл стилей — style.css и подключим его в наших файлах:

НОВОСТИ

«content» >

Новость 1

Краткое содержание новости 1: CSS-ссылки содержат свойства.
.Краткое содержание новости 1: CSS-ссылки содержат свойства.

.
. Новость 2.
. Новость 3.
. Новость 4.
.

Новость 5

Краткое содержание новости 5: CSS-ссылки содержат свойства.
.Краткое содержание новости 5: CSS-ссылки содержат свойства.

Аналогично, в папке views/news/index.php создадим файл view.php — для экшена actionView($id) (Просмотр одной новости).

НОВОСТИ

«content» >

Новость 1

Содержание новости 1

В папке tamplate разместим файл стилей — style.css и подключим его в наших файлах:

* margin : 0;
padding : 0;
box-sizing : border-box;
/* transition: .5s ease-in-out ; */
>

body font : 90%/1.5em verdana, arial, helvetica, sans-serif;
color :#000 ;
>

# wrap <
position : relative ;
min-height : 100%;
padding-bottom : 50px; /*отступ величиной с высоту футера*/
>

. head margin : 0 auto;
max-width : 100%;
background-image : linear-gradient( white ,#cecece );
background-size : cover;
-webkit-background-size : cover;
-moz-background-size : cover;
height : 100px;
text-align : center;
>

h1 padding : 30px;
color : orange;
>

# content <
margin : 0 auto 0 auto; /*Поочередно устанавливается отступ от верхнего, правого, нижнего и левого края.*/
width : 90%;
overflow :auto ;
border : solid 1px red;
>

. post float : left;
width : 50%;
margin : 20px 0 20px;
overflow : hidden;
background : #F5F5F5;
text-align : center;
border: solid 5px #fff;
>

. title padding-top : 10px;
letter-spacing : -2px;
>

. title a border : none;
text-decoration : none;
>

. post-news width : 100%;
margin : 20px 0 20px;
background : #F5F5F5;
text-align : center;
: ;
>

. byline display : block;
padding : 2px 5px 2px 0px;
background : #F5F5F5;
text-align : center;
text-transform : uppercase;
font-size : 10px;
color : gray;
>

. entry text-align : left;
margin-bottom : 25px;
overflow : hidden;
padding : 10px 25px 0px 25px ;
font-size : 0.9rem;
height : 50px;
margin-bottom : 1rem;
>

. links display : block;
padding : 2px 0px 2px 25px;
text-align : left;
text-transform : uppercase;
font-size : 10px;
color : #FFFFFF;
>

. post-news . links display : block;
padding : 2px 25px 2px 10px;
text-align : right;
text-transform : uppercase;
font-size : 10px;
color : #FFFFFF;
>

. post-news . entry text-align : left;
margin-bottom : 25px;
overflow : visible;
height : 100%;
padding : 10px 25px 0px 25px;
font-size : 0.9rem;
margin-bottom : 1rem;
>

. post-news . title padding-top : 10px;
letter-spacing : -2px;
color : darkcyan;
>

. post-news . title padding-top : 10px;
letter-spacing : -2px;
color : darkcyan;
>

# footer position : absolute;
bottom : 0;
width : 100%;
height : 50px;
background-image : linear-gradient( #cecece, white );
>

В файле .htaccess мы написали перенаправления для всех запросов на файл index.php.

Для того, чтобы файл style.css и изображения (images/img. ) работали, добавляем еще два правила:

AddDefaultCharset utf- 8
RewriteEngine On
RewriteCond % !-f
RewriteCond % !-d
RewriteRule ^(.*)$ index.php

Файловая структура сайта test2 :

MVC-5-2

MVC-5-3

Страница просмотра одной новости

MVC-5-4

Далее наша задача состоит в том, чтобы получить информацию из элементов массива $newsList (контроллер NewsController.php) и разместить ее на странице news/index.php

Выбираем один шаблон, который соответствует одной новости на странице и в цикле foreach ($newsList as $newsItem) заменяем статические данные , на данные, полученые из массива $newsList ( распечатываем элементы массива ).
Используем, при этом, сокращенный синтаксис :

— заголовки новостей
/news/ — ссылка на эту новость (по индификатору ‘id’ и пути ‘/news’)
— дата добавления новости
— краткое содержание новости
/news/ — еще одна ссылка на новость (по индификатору ‘id’ и пути ‘/news’)

НОВОСТИ

Источник

Читайте также:  Functional programming in javascript pdf
Оцените статью