PHPackages                             zackhine/view-element.php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. zackhine/view-element.php

ActiveLibrary[Templating &amp; Views](/categories/templating)

zackhine/view-element.php
=========================

PHP Template Engine that blurs the line between Markup and PHP

v1.0.1(10y ago)017MITPHPPHP &gt;=5.3.0

Since Jul 4Pushed 10y ago1 watchersCompare

[ Source](https://github.com/ZackHine/ViewElement.php)[ Packagist](https://packagist.org/packages/zackhine/view-element.php)[ RSS](/packages/zackhine-view-elementphp/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (3)Used By (0)

ViewElement.php [![Latest Stable Version](https://camo.githubusercontent.com/ce114c842260d6451f7d686ec428bcc9f990eb1614bbc83f8ed0d9e3decb37df/68747470733a2f2f706f7365722e707567782e6f72672f7a61636b68696e652f766965772d656c656d656e742e7068702f762f737461626c65)](https://packagist.org/packages/zackhine/view-element.php) [![Total Downloads](https://camo.githubusercontent.com/9b8bb8b118ceb0e428c85a512ab40e7dba3a62cc53226e36fdf57c3a42c5933a/68747470733a2f2f706f7365722e707567782e6f72672f7a61636b68696e652f766965772d656c656d656e742e7068702f646f776e6c6f616473)](https://packagist.org/packages/zackhine/view-element.php) [![Latest Unstable Version](https://camo.githubusercontent.com/9d3ce481531c8876305efd9241eebf88c99700b57adc70d69930a3c5ca4e4f4a/68747470733a2f2f706f7365722e707567782e6f72672f7a61636b68696e652f766965772d656c656d656e742e7068702f762f756e737461626c65)](https://packagist.org/packages/zackhine/view-element.php) [![License](https://camo.githubusercontent.com/679e405c35d6fd4e2c8025c0992bef936ed8d8a143c69bd5df9f1eb0abf93b00/68747470733a2f2f706f7365722e707567782e6f72672f7a61636b68696e652f766965772d656c656d656e742e7068702f6c6963656e7365)](https://packagist.org/packages/zackhine/view-element.php)
=====================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#viewelementphp----)

> PHP Template Engine that blurs the line between Markup and PHP

Purpose
=======

[](#purpose)

ViewElement.php is built with Separation of Concerns in mind. It's too easy to write bad PHP code that mixes PHP with HTML. This can become incredibly hard if not impossible to maintain.

Even in other popular templating engines, there is still a lot of "pseudo-code" written in HTML files. ViewElement.php makes it easier than ever to not include code in your HTML files. It does this by converting HTML files into PHP Classes and giving the Classes access to what we call "ViewElements". ViewElements are any HTML elements the programmer wants to be able to modify via PHP.

After the ViewElements are programmatically modified to the programmer's liking, the generated PHP Class is then converted back into HTML and can be returned to the browser.

ViewElement.php is very flexible and can be used to generate any HTML file imaginable.

How to Use
==========

[](#how-to-use)

ViewElement.php achieves what it sets out to do by creating a 2-step process. The first step is converting HTML files into PHP Classes through a Phing Build Task. The second step is giving the programmer the ability to modify those PHP Classes in any way they want before converting the result back into HTML.

Install
-------

[](#install)

It is recommended that you use Composer to install this library. To do that, your composer.json file should have the following:

```
"require": {
    "php": ">=5.3.0",
    "zackhine/view-element.php": "1.*"
  }

```

If you don't want to use Composer you could download the source here and include the library in your application. Just be weary that the documentation here is written assuming Composer is being used. Thus, if you're not using Composer some things like paths could end up being different.

Phing Build
-----------

[](#phing-build)

One of the nicest features of ViewElement.php is all of the would-be repetitive work is handled by a Phing Build Task. The GenerateView Task looks through all of your HTML files that you pass to it and converts them into PHP Classes. The Classes can then be used in your application code to set up your view. In order to get the GenerateView Task working please read the information below:

### view-element-build.json

[](#view-element-buildjson)

The view-element.build.json file is the configuration file for the GenerateView Phing Task. This file must be at the root of your project and currently must exist.

There are 4 properties that can all be optionally added which will be discussed below. For reference, an example view-element-build.json file looks like:

```
{
  "view-element": "ALViewElement",
  "view-file-root": "tests",
  "dir-sep": "/",
  "namespaces": [
    {
      "commands\\User\\view\\": "commands\\User\\view"
    },
    {
      "commands\\Admin\\view\\": "commands\\Admin\\view"
    },
    {
      "commands\\common\\view\\": "commands\\Common\\view"
    }
  ]
}

```

#### view-element *(Optional)*:

[](#view-element-optional)

This is what the GenerateView Task will look for on your HTML elements to know which ViewElements to create in the generated View files. The task will look for:

```
id="{{[view-element-property]_yourElementId}}"

```

If this is not included in your view-element-build.json file, the default value is "ViewElement". An example of this would look like:

```

```

An example that would work with the reference view-element-build.json included above would look like:

```

```

#### view-file-root *(Optional)*:

[](#view-file-root-optional)

This is only needed if your view-element-build.json and build.xml files are not at the root of your project. For example, in this project view-element-build.json and build.xml were located at this location:

```
- project root
    - tests
        - build.xml
        - view-element-build.json

```

The value for this property **must** be relative your project root.

#### dir-sep *(Optional)*:

[](#dir-sep-optional)

The generated PHP View Classes all implement the IView Interface. One method of the IView interface is getViewFile which must return the path to the HTML file the PHP Class is generated from relative the project root. The dir-sep property can be used to tell the GenerateView Task what to use as a directory separator in this path.

For example if you have the following:

```
"dir-sep": "/"

```

Then the generated getViewFile method would look something like:

```
 public function getViewFile() {
        return "path/to/yourView.html";
 }

```

If this property is not included, then GenerateView will use the value obtained by calling "DIRECTORY\_SEPARATOR" in PHP.

#### namespaces *(Optional)*:

[](#namespaces-optional)

The namespaces property expects an array mapping source paths to namespaces. The GenerateView Task will use the path of the HTML file passed in to look into this mapping to find what value should be used as the namespace in the generated PHP View Class file. If GenerateView cannot find the path, there will be no namepsace in the generated Class.

build.xml
---------

[](#buildxml)

With your view-element-build.json file configured correctly, you can run the GenerateView Phing task to generate PHP Classes based off HTML Templates.

To get this working, you must do three things in your build.xml file:

1. include composer autoload.php in your build.xml

    ```

    ```
2. Define the GenerateView Task

    ```

    ```
3. Pass the file name for each HTML file you want to generate a PHP Class for into the generateview task

    ```

    ```

For reference, a complete build.xml file is included below:

```

```

Running build
-------------

[](#running-build)

I recommend using [PhpStorm](https://www.jetbrains.com/phpstorm/) for PHP Development. PhpStorm makes it very easy to run a Phing Build. Please see this page for instructions:

[Phing Build using PhpStorm](https://www.jetbrains.com/phpstorm/help/enabling-phing-support.html)

Usage in your code
------------------

[](#usage-in-your-code)

All of the below code snippets come from tests/test.php in this project

### require in source

[](#require-in-source)

Once all of your files have been generated, it's easy to use ViewElement.php in your project.

All you need to do is include the composer autoload.php file:

```
require_once __DIR__ . '/vendor/autoload.php';

```

### View

[](#view)

The generated PHP View Class has three main purposes for the programmer.

1. Initializing the View
2. Provide access to the ViewElements
3. The create method

### Initializing the View:

[](#initializing-the-view)

You initialize the View by using it's constructor:

```
$commonView = new \commands\Common\view\CommonView();

```

#### Provide access to the ViewElements:

[](#provide-access-to-the-viewelements)

Every ViewElement in a View Class can be accessed directly:

```
$commonView->homeItem

```

### The create method:

[](#the-create-method)

The create method is what is used to generate the view once you have configured each ViewElement. This will return the generated DOM as a string. This string can then be returned to the browser:

```
echo $commonView->create();

```

### ViewElement

[](#viewelement)

The ViewElements which are accessed via the PHP View Class are what the programmer uses to alter the view in whatever way they need to. ViewElements provide an API for easy configuration:

#### setContent/getContent

[](#setcontentgetcontent)

setContent is used to set the content inside the HTML Element the ViewElement represents. If there is already HTML content inside the ViewElement, the content added via setContent will be placed before the existing content.

You can only call setContent one time per ViewElement. Calling it more than once will overwrite the previous call.

getContent will simply return the content you've already set.

HTML:

```

```

PHP:

```
 $commonView->homeHeaderNavTitle->setContent("Admin Options");

```

Generated HTML:

```
Admin Options

```

#### appendContent

[](#appendcontent)

appendContent is similar to setContent except that it does allow you to call it multiple times. Also, if there is already HTML content inside the ViewElement, the content added via appendContent will be placed after this existing content.

getContent works the same way when paired with appendContent as it does with setContent.

HTML:

```
Messages

```

PHP:

```
$commonView->messagesItem->appendContent(" 2");

```

Generated HTML:

```
Messages 2

```

#### setAttribute/getAttribute

[](#setattributegetattribute)

setAttribute is used to set an attribute on the HTML Element the ViewElement represents. The attribute does **not** need to already exist on the HTML element. If it does not it will be created and the value will be added. Like setContent, calling this method multiple times will overwrite what you have already set. Also, if the given attribute already exists in the raw HTML, that will be overwritten as well.

getAttribute takes a string as a parameter and returns the value you've set for that attribute.

HTML:

```
Home

```

PHP:

```
$commonView->homeItem->setAttribute("class", "active");

```

Generated HTML:

```
Home

```

#### appendAttribute

[](#appendattribute)

appendAttribute is similar to setAttribute except that it appends the value given to the attribute name passed in instead of overwriting it.

getAttribute works the same way when paired with appendAttribute as it does with setAttribute.

HTML:

```

```

PHP:

```
$commonView->userImg->appendAttribute("src", $user->getUserId());

```

Generated HTML:

```

```

#### remove

[](#remove)

The remove method is used to remove the HTML Element the ViewElement represents from the DOM. When the HTML is generated the HTML Element will no longer exist.

HTML:

```

    Home
    Messages
    Admin Access

```

PHP:

```
$commonView->adminAccessItem->remove();

```

Generated HTML:

```

    Home
    Messages

```

#### removeIdAfterCreation

[](#removeidaftercreation)

Sometimes you may want to define a ViewElement so that you can modify it, but you may not want an id on the HTML Element when it's generated. You can use removeIdAfterCreation to assure the generated HTML Element will not have an id.

HTML:

```

    Admin Action 1
    Admin Action 2
    Admin Action 3

```

PHP:

```
 $adminHomeView->adminAction1->removeIdAfterCreation();
 $adminHomeView->adminAction2->removeIdAfterCreation();
 $adminHomeView->adminAction3->removeIdAfterCreation();

```

Generated HTML:

```

    Admin Action 1
    Admin Action 2
    Admin Action 3

```

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

3971d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b3b37b15ee8034b0a62f45e8926e43967947ff6a79057e3ce116fc42fe8b91bf?d=identicon)[ZackHine](/maintainers/ZackHine)

---

Top Contributors

[![ZackHine](https://avatars.githubusercontent.com/u/8602204?v=4)](https://github.com/ZackHine "ZackHine (24 commits)")

---

Tags

templating

### Embed Badge

![Health badge](/badges/zackhine-view-elementphp/health.svg)

```
[![Health](https://phpackages.com/badges/zackhine-view-elementphp/health.svg)](https://phpackages.com/packages/zackhine-view-elementphp)
```

###  Alternatives

[twig/twig

Twig, the flexible, fast, and secure template language for PHP

8.4k443.2M5.8k](/packages/twig-twig)[mustache/mustache

A Mustache implementation in PHP.

3.3k44.6M291](/packages/mustache-mustache)[smarty/smarty

Smarty - the compiling PHP template engine

2.3k39.1M395](/packages/smarty-smarty)[timber/timber

Create WordPress themes with beautiful OOP code and the Twig Template Engine

5.7k3.4M111](/packages/timber-timber)[league/plates

Plates, the native PHP template system that's fast, easy to use and easy to extend.

1.5k5.9M232](/packages/league-plates)[eftec/bladeone

The standalone version Blade Template Engine from Laravel in a single php file

8208.4M87](/packages/eftec-bladeone)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
