+ - 0:00:00

Yii Framework 2.0

Vortrag 12.03.2014 - PHPugS

Tobias Munk, herzog kommunikation GmbH, Stuttgart

Entwickler von Phundament & Yii Framework Enthusiast

1 / 38

Was Bots über mich sagen...

Tobias Munk is an awesome PHP coder (one of the 3% most active PHP users) who loves pushing code. Tobias is a nine-to-fiver who works best in the evening (around 6 pm).

Tobias has contributed to repositories in 13 languages. In particular, Tobias seems to be a pretty serious PHP expert. The following chart shows the number of contributions Tobias made to repositories mainly written in PHP, JavaScript, CSS, Ruby, and Shell.

http://osrc.dfm.io/schmunk42

... und ich selbst

  • seit 15 Jahren HTML, CSS, JavaScript und PHP Entwickler
  • Verantwortlich für Umsetzung verschiedenster Websites, Web-Applikationen und iOS/Android Anwendungen als Geschäftsführer der herzog kommunikation GmbH
  • Open-Source Fan
2 / 38

Einführung

3 / 38

Was ist Yii?

Yii is a high-performance, component-based PHP framework for rapidly developing large-scale Web applications. Yii enables maximum reusability in Web programming and can significantly accelerate your Web application development process. The name Yii (pronounced Yee or [ji:]) is an acronym for Yes It Is!.

Yii is a generic Web programming framework that can be used for developing virtually any type of Web application. Because it is light-weight and equipped with sophisticated caching mechanisms, Yii is especially suited to high-traffic applications such as portals, forums, content management systems (CMS), e-commerce projects, and so on.

Nicht: Gii (Sprich: Tschii). Das gibt es auch, ist aber "nur" Yiis Code Generator, dazu kommen wir später ;)

Referenz: http://stuff.cebe.cc/yii2docs/guide-overview.html

4 / 38

Features

  • PHP >=5.4.0
  • pure OOP framework
  • namespaces
  • performance
    • light-weight and equipped with sophisticated caching mechanisms
    • especially suited to high-traffic applications such as portals
  • MVC (Model-View-Controller) Design
  • generic Web programming framework
    • good balance between simplicity and features
  • great code-syntax and overall development workflow
  • heavily influenced by Ruby on Rails
    • Still, no framework or feature is being blindly copied into Yii
  • all decisions are based upon what's best for Web developers and in keeping with Yii's philosophy.

Zusätzlich...

  • große Community (150.000+ Forum-User, 225.000+ Postings)
  • sehr gute Dokumentation
  • sehr kompetentes Core-Team mit Qiang, Samdark und CeBe und Anderen.
5 / 38

PHP 5.4

Short Echo

<p>Hello, <?= $username ?>!</p>

Short Arrays

public function actionIndex()
{
    return $this->render('index', ['username' => 'samdark']);
}

Traits

class ActiveQuery extends Query implements ActiveQueryInterface
{
    use ActiveQueryTrait;
    use ActiveRelationTrait;

[...]
6 / 38

Verwandte Projekte

  • Symfony
  • Laravel
  • Zend Framework
  • CodeIgniter

Yii 2 selbst ist nicht so stark komponenten-basiert wie die og. Projekte, hält aber eine sehr gute Balance zwischen Modularität und Konsistenz und lässt sich hervorragend mit Komponenten dieser Frameworks nutzen.

7 / 38

Änderungen zu 1.1

Ausschnitt

  • Namespaces, kein C-Prefix mehr
  • Aufsplittung in Component & Object
  • Events
  • Pfad-Aliase (Bsp. @yii)
  • View Application Component
    • Zugriff auf Controller oder Widget mit $this->context
    • Ersatz für CClientScript
    • Renderer & Template Engines
  • Models, Widgets
  • Themes
    • inkl. Suchpfade und Aliase für Templates
  • Konsolen-Applikationen (controller/action-style)
  • AssetBundles
    • Ersatz für ClientScript Packages
  • Composer - Dependency Manager für 3rd-party Extensions

Yii 2.0 und die Extensions sind nicht abwärtskompatibel mit 1.1, Portierungen sind aber mehrheitlich Fleißarbeit, ein Refactoring sollte man trotzdem einplanen.

Referenz: http://stuff.cebe.cc/yii2docs/guide-upgrade-from-v1.html

8 / 38

Entwicklungsstand

Stand: Mitte März 2014

  • 6000+ commits, fast 2000 Stargazers auf github, über 150 Contributors
  • Qiang war der "most-active"(!) User auf github in den letzten 12 Monaten (Februar 2014)
  • Oh no! It's alpha ... aber die API ist zu 90% stable!
  • Beta-Release Ende März
  • hervorragende Core-Extensions
    • apidoc (Dokumentation)
    • authclient (OpenID, OAuth und OAuth2)
    • bootstrap (UI Framework)
    • codeception (Testing Framework)
    • debug (App-Info, Logging, Profiling)
    • elasticsearch, mongodb, sphinx (Suche und Dokumenten-DBs)
    • faker (Test/Demo-Daten)
    • gii (Code-Generierung)
    • imagine (Bildmanipulation)
    • jquery, jui (JavaScript libs)
    • redis (Cache)
    • smarty, twig (Template Engines)
    • swiftmailer (E-Mailer)
  • aktuell >200 Extensions, sowie verschiedene Skeleton Apps verfügbar...
9 / 38

Die Apps

Die Struktur der Anwendung kann in Yii nahezu frei gewählt werden

10 / 38

Basic App

basic/
├── LICENSE.md
├── README.md
├── assets
├── codeception.yml
├── commands
├── composer.json
├── composer.lock
├── config
├── controllers
├── models
├── requirements.php
├── runtime
├── tests
├── vendor
├── views
├── web
├── yii
└── yii.bat

Details: http://stuff.cebe.cc/yii2docs/guide-apps-basic.html

11 / 38

Advanced App

advanced/
├── LICENSE.md
├── README.md
├── backend
│   ├── [...]
├── common
│   ├── [...]
├── composer.json
├── console
│   ├── [...]
├── environments
├── frontend
│   ├── [...]
├── init
├── init.bat
├── requirements.php
├── vendor
└── yii.bat

http://stuff.cebe.cc/yii2docs/guide-apps-advanced.html

13 / 38

Phundament

v4/
├── LICENSE.md
├── README.md
├── Vagrantfile
├── app
│   ├── [...]
├── codeception.yml
├── composer.json
├── composer.lock
├── puphpet
├── requirements.php
├── vendor
├── web
├── yii
└── yii.bat

https://github.com/phundament/app/tree/4.0

14 / 38

MVC - Struktur

structure

Referenz: http://stuff.cebe.cc/yii2docs/guide-mvc.html

15 / 38

MVC - Flow

flow

16 / 38

Installation

17 / 38

Composer

Wer noch keinen composer auf seiner Entwicklungsmaschine hat: https://getcomposer.org/download/. Eine globale Installation ist empfohlen.

via Kommandozeile

composer.phar create-project phundament/app:4.0.x-dev phpugs-app

Dieser Befehl installiert ein Anwendungsgerüst (Skeleton), lädt die entsprechenden Pakete in den vendor Ordner, aktualisiert den Autoloader und setzt die nötigen Dateirechte.

Möchte man an Yii 2 selbst mitentwickeln, muss man das Framework und die Extensions über das yii2-dev Paket installieren. Mehr Infos dazu finden sich im Guide.

Live-Demo

http://localhost/gitlab/phundament/phpugs-app/web/

install

18 / 38

Entwicklung

19 / 38

Model

DAO

Durch Namespaces ist das Autoloading nur ein use Statement:

use \vendor\package\MyOldBlog as Post;

Erstellen eines neuen Datensatzes:

$post = new Post();
$post->title = 'Hello, world';
$post->content = 'Something interesting is happening.';
$post->save();

Model-Klassen implementieren:

  • Datenbank-Zugriff
  • Attribute-Labels
  • Scenarios
  • Validation
  • Mass-Assignment

Referenz: http://stuff.cebe.cc/yii2docs/guide-model.html

20 / 38

Controller & View

The view component is an important part of MVC. The view acts as the interface to the application, making it responsible for presenting data to end users, displaying forms, and so forth.

By default, Yii uses PHP in view templates to generate content and elements. A web application view typically contains some combination of HTML, along with PHP echo, foreach, if, and other basic constructs. Using complex PHP code in views is considered to be bad practice. When complex logic and functionality is needed, such code should either be moved to a controller or a widget.

The view is typically called from controller action using the render() method:

public function actionIndex()
{
    return $this->render('index', [
        'username' => 'samdark',
        'items' => $this->getMenuItems(),
    ]);
}

Referenz: Guide Controller, View s.a. Routing, Exkurs: Templay (dev)

21 / 38

Widgets

Menü

echo \yii\widgets\Menu::widget(['items' => $items]);

Formular

// Passing an array to initialize the object properties
$form = \yii\widgets\ActiveForm::begin([
    'options'     => ['class' => 'form-horizontal'],
    'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
]);

... form inputs here ...

\yii\widgets\ActiveForm::end();

http://stuff.cebe.cc/yii2docs/guide-view.html

22 / 38

Core Extensions

Bootstrap-Button

HTML Plain

<a class="btn btn-lg">Action</a>

PHP Yii-Extension

<?= yii\bootstrap\Button::widget([
    'label' => 'Action',
    'options' => ['class' => 'btn-lg'],
]); ?>

Referenz: http://stuff.cebe.cc/yii2docs/ext-bootstrap-index.html

Mongo DB mit Active Record

Referenz: http://stuff.cebe.cc/yii2docs/ext-mongodb-index.html

ApiDoc

vendor/bin/apidoc api source/directory ./output
vendor/bin/apidoc guide source/docs ./output

Referenz: http://stuff.cebe.cc/yii2docs/ext-apidoc-index.html

23 / 38

3rd Party-Extensions

Gravatar

Extension in die Anwendung holen:

composer.phar require cebe/yii2-gravatar

Use Statement:

use \cebe\gravatar\Gravatar;

Template-Code:

<?= Html::a(
    Gravatar::widget([
        'email'   => $author->email,
        'size'    => 32
    ]),
    ['/profile/', 'username' => $author->name]
); ?>

Der HTML Helper ersetzt die Klasse CHtml aus Yii 1.1. Sie verbindet Framework-Funktionen und das rendering von HTML Tags wie Links, Images, Form-Inputs, ...

24 / 38

Packaii

Paketbrowser (alpha), Konfiguration eines Moduls:

'modules'        => [
    'packaii' => [
        'class' => 'schmunk42\packaii\Module'
    ],

Live Demo

packaii

25 / 38

Gii - Code Genrator

Extensions, Models, CRUDs

Live Demo

gii

26 / 38

Specials

27 / 38

pjax = pushState + ajax

pjax is a jQuery plugin that uses ajax and pushState to deliver a fast browsing experience with real permalinks, page titles, and a working back button.

pjax works by grabbing html from your server via ajax and replacing the content of a container on your page with the ajax'd html. It then updates the browser's current url using pushState without reloading your page's layout or any resources (js, css), giving the appearance of a fast, full page load. But really it's just ajax and pushState.

<?php Pjax::begin([
    'id' => 'detail-panel',
    'linkSelector' => 'a.package-link',
    'timeout' => 10000
]); ?>

<?= Html::a($model->name, Html::url([
    'detail',
    'name' => $model->name,
    'version' => $version
]), ['class' => 'package-link']) ?>

<?php Pjax::end(); ?>

Referenz: https://github.com/defunkt/jquery-pjax, Demo schmunk42/yii2-packaii

28 / 38

Asset Bundles

  • CSS, JavaScript
  • Assent Konverter für: LESS, SCSS, Stylus, CoffeeScript, TypeScript
  • Abhängigkeiten zwischen Asset Bundles
  • Kompression
<?php
use yii\web\AssetBundle as AssetBundle;

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

Referenz: http://stuff.cebe.cc/yii2docs/guide-assets.html

29 / 38

Behaviors (aka Mixin)

Beispiele aus Yii 1

  • Audittrail, Active Record (AR) Logging
  • Translatable, AR Attribut-Übersetzungen aus Relationstabelle
  • Access, AR ACL Implmentierung
  • Nested Set, AR Baumstrukturen

Referenz: http://stuff.cebe.cc/yii2docs/guide-behaviors.html

30 / 38

Events

Event absetzen, nachdem sich ein Benutzer registriert hat:

class UserManagement extends Component
{
    public function registerUser()
    {
        $this->trigger('userRegistered');
    }
}

Konfiguration von "Custom-Code" in der App-Konfiguration:

return [
    // ...
    'components' => [
        'user' => [
            'on userRegistered' => function ($event) {
                // do something right after a user has registered
            }
        ],
    ],
];

Referenz: http://stuff.cebe.cc/yii2docs/guide-events.html

31 / 38

Pfad-Aliase

  • @app
  • @yii
  • @vendor

Kann mit praktisch allen Funktionsaufrufen und in der Konfiguration benutzt werden.

Yii 2.0 expands the usage of path aliases to both file/directory paths and URLs. An alias must start with a @ character so that it can be differentiated from file/directory paths and URLs. For example, the alias @yii refers to the Yii installation directory while @web contains base URL for currently running web application. Path aliases are supported in most places in the Yii core code. For example, FileCache::cachePath can take both a path alias and a normal directory path.

Referenz: http://stuff.cebe.cc/yii2docs/guide-basics.html#path-aliases

32 / 38

Caching mit Abhängigkeiten

use yii\caching\FileDependency;

// the value will expire in 30 seconds
// it may also be invalidated earlier if the dependent file is changed

Yii::$app->cache->set(
    $id, 
    $value, 
    30, 
    new FileDependency(['fileName' => 'example.txt'])
);

Verfügbare Dependency-Klassen:

  • yii\caching\DbDependency
  • yii\caching\ExpressionDependency
  • yii\caching\FileDependency
  • yii\caching\GroupDependency
  • yii\caching\ChainedDependency

Dependencies können über eine Chained Dependency kombiniert werden.

33 / 38

Virtualisierung

Vagrant

Konfiguration von benötigten PHP-Extensions, z.B. MongoDB, in puphpet/config.yaml

composer.phar create-project --no-install phundament/app:4.0.x-dev \
  phpugs-vagrant 
cd phpugs-vagrant/

VM starten:

vagrant up --provision

Go to: http://192.168.33.101

Virtualisierung mit verschiedenen Providern, Default: VirtualBox. Instant Deployment zu u.a. AWS EC2, Digital Ocean, Managed Server u.v.m. Konfiguration über ENV-Vars oder Datei.

vagrant up --provider=aws

Live Demo

vagrant

34 / 38

Testing

Einloggen auf die VM:

vagrant ssh

Testsuites laufen lassen:

vendor/bin/codeception run

* Untested ;)

Committing

Hinweis: Die Datei composer.lock sollte in den Projekten mitcomittet werden um immer einen konsistenten Projektstand zu bekommen.

Der Befehl composer.phar install installiert exakt die Revisions aus dem lock-file.

Commit your application's composer.lock (along with composer.json) into version control.

Referenz: https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file

35 / 38

Links

Yii Framework

* Die URLs der Dokumentation unter stuff.cebe.cc ist temporär, wird aber später auf die offizielle Publikation weitergeleitet.

Phundament

Markdown Präsentation

36 / 38

Fragen?

37 / 38

Vielen Dank!

Speziell and Tony, Fredrik, Chris, Mike und an das Yii-Core Team.

38 / 38

Was Bots über mich sagen...

Tobias Munk is an awesome PHP coder (one of the 3% most active PHP users) who loves pushing code. Tobias is a nine-to-fiver who works best in the evening (around 6 pm).

Tobias has contributed to repositories in 13 languages. In particular, Tobias seems to be a pretty serious PHP expert. The following chart shows the number of contributions Tobias made to repositories mainly written in PHP, JavaScript, CSS, Ruby, and Shell.

http://osrc.dfm.io/schmunk42

... und ich selbst

  • seit 15 Jahren HTML, CSS, JavaScript und PHP Entwickler
  • Verantwortlich für Umsetzung verschiedenster Websites, Web-Applikationen und iOS/Android Anwendungen als Geschäftsführer der herzog kommunikation GmbH
  • Open-Source Fan
2 / 38
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
f Toggle fullscreen mode
c Clone slideshow
p Toggle presenter mode
w Pause/Resume the presentation
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow