10 PHP Frameworks For Developers

PHP, known as the most popular server-side scripting language in the world, has evolved a lot since the first inline code snippets appeared in static HTML files. These days developers need to build complex websites and web apps, and above a certain complexity level it can take too much time and hassle to always start from scratch, hence came the need for a more structured natural way of development. PHP frameworks provide developers with an adequate solution for that.

In this post we carefully handpicked 10 popular PHP frameworks that can bestfacilitate and streamline the process of backend web development.

Why Use A PHP Framework

But first, let’s take a look at the top reasons why many developers like to use PHP frameworks and how these frameworks can level up your development process. Here’s what PHP frameworks do:

  • Make speed development possible
  • Provide well-organized, reusable and maintainable code
  • Let you grow over time as web apps running on frameworks are scalable
  • Spare you from the worries about low-level security of a site
  • Follow the MVC (Model-View-Controller) pattern that ensures the separation of presentation and logic
  • Promote modern web development practices such as object-oriented programming tools

1. Laravel

Although Laravel is a relatively new PHP framework (it was released in 2011), according to Sitepoint’s recent online survey it is the most popular framework among developers. Laravel has a huge ecosystem with an instant hosting and deployment platform, and its official website offers many screencast tutorials called Laracasts.

Laravel has many features that make rapid application development possible. Laravel has its own light-weight templating engine called “Blade”, elegant syntax that facilitates tasks you frequently need to do, such as authentication, sessions, queueing, caching and RESTful routing. Laravel also includes a local development environment called Homestead that is a packaged Vagrant box.

2. Symfony

The components of the Symfony 2 framework are used by many impressive projects such as the Drupal content management system, or the phpBB forum software, but Laravel – the framework listed above – also relies on it. Symfony has a wide developer community and many ardent fans.

Symfony Components are reusable PHP libraries that you can complete different tasks with, such as form creation, object configuration, routing, authentication, templating, and many others. You can install any of the Components with the Composer PHP dependency manager. The website of Symfony has a cool showcase section where you can take a peek at the projects developers accomplished with the help of this handy framework.

3. CodeIgniter

CodeIgniter is a lightweight PHP framework that is almost 10 years old (initially released in 2006). CodeIgniter has a very straightforward installation process that requires only a minimal configuration, so it can save you a lot of hassle. It’s also an ideal choice if you want to avoid PHP version conflict, as it works nicely on almost all shared and dedicated hosting platforms (currently requires only PHP 5.2.4).

CodeIgniter is not strictly based on the MVC development pattern. Using Controller classes is a must, but Models and Views are optional, and you can use your own coding and naming conventions, evidence that CodeIgniter gives great freedom to developers. If you download it, you’ll see it’s only about 2MB, so it’s a lean framework, but it allows you to add third-party plugins if you need more complicated functionalities.

4. Yii 2

If you choose the Yii framework you give a boost to the performance of your site as it’s faster than other PHP frameworks, because it extensively uses the lazy loading technique. Yii 2 is purely object-oriented, and it’s based on theDRY (Don’t Repeat Yourself) coding concept, so it provides you with a pretty clean and logical code base.

Yii 2 is integrated with jQuery, and it comes with a set of AJAX-enabled features, and it implements an easy-to-use skinning and theming mechanism, so it can be a great choice for someone who comes from a frontend background. It has also a powerful class code generator called Gii that facilitates object-oriented programming and rapid prototyping, and provides a web-based interface that allows you to interactively generate the code you need.

5. Phalcon

The Phalcon framework was released in 2012, and it quickly gained popularity among PHP developers. Phalcon is said to be fast as a falcon, because it waswritten in C and C++ to reach the highest level of performance optimization possible. Good news is that you don’t have to learn the C language, as the functionality is exposed as PHP classes that are ready to use for any application.

As Phalcon is delivered as a C-extension, its architecture is optimized at low levels which significantly reduces the overhead typical of MVC-based apps. Phalcon not only boosts execution speeds, but also decreases resource usage. Phalcon is also packed with many cool features such as a universal auto-loader, asset management, security, translation, caching, and many others. As it’s awell-documented and easy-to-use framework, it’s definitely worth a try.

6. CakePHP

CakePHP is already a decade old (the first version was released in 2005), but it’s still among the most popular PHP frameworks, as it has always managed to keep up with time. The latest version, CakePHP 3.0 enhanced session management,improved modularity by decoupling several components, and increased the ability of creating more standalone libraries.

CakePHP has a really remarkable showcase, it powers the websites of big brands such as BMW, Hyundai, and Express. It is an excellent tool for creating web apps that need high-level of security, as it has many built-in security features such as input validation, SQL injection prevention, XSS (cross-site scripting) prevention, CSRF (cross-site request forgery) protection, and many others.

7. Zend Framework

Zend is a robust and stable PHP framework packed with a lot of configuration options therefore it’s usually not recommended for smaller projects butexcellent for more complex ones. Zend has partners such as IBM, Microsoft, Google and Adobe. The coming major release, Zend Framework 3 will beoptimized for PHP 7 , but will still support PHP 5.5 onwards.

The current release, Zend Framework 2 also has many cool features such as cryptographic coding tools, an easy-to-use drag and drop editor with support for front-end technologies (HTML, CSS, JavaScript), instant online debugging and PHP Unit testing tools, and a connected Database Wizard. Zend Framework was created with the Agile methodology that facilitates delivering high-quality apps to enterprise clients.

8. Slim

Slim is a PHP micro framework that provides you with everything you need and nothing you don’t. Micro frameworks are minimalistic in design, they areexcellent for smaller apps where a full-stack framework would be an exaggeration. Slim’s creator was inspired by a Ruby micro framework calledSinatra.

Slim is used by many PHP developers for developing RESTful APIs and services. Slim comes with features such as URL routing, client-side HTTP caching, session- and cookie encryption, and it supports “flash” messages across HTTP requests as well. Its User Guide is an easy read, and if you are interested in the new features of the upcoming major release (already in beta), you can watch this primer video about Slim 3.

9. FuelPHP

FuelPHP is a flexible full-stack PHP framework that doesn’t only support the ordinary MVC pattern but also its evolved version, HMVC (Hierarchical Model-View-Controller) at the architecture level. FuelPHP adds an optional classcalled Presenter (formerly called ViewModel) between the Controller and View layers to hold the logic needed to generate Views.

FuelPHP is modular and extendable, takes care of security concerns by providing features such as input and URI filtering and output encoding, and it comes with its own authentication framework, with many other sophisticatedfeatures and a detailed documentation.

10. PHPixie

PHPixie is a quite new framework, it started in 2012 with the goal of creating a high-performance framework for read-only websites. PHPixie also implements the HMVC design pattern just like FuelPHP, and is built by using independentcomponents that can be used as well without the framework itself. The PHPixie components are 100% unit tested, and require minimum dependencies.

The official website has a tutorial that claims you can learn the framework in 30 minutes, and their blog also details many practical use cases. Among the features you can find the standard ORM (object-relational mapping), caching, input validation, authentication and authorization capabilities. PHPixie also allows you to use the HAML markup language, enables schema migration, and has a sophisticated routing system.

Fonte: 10 PHP Frameworks For Developers – Best Of – Hongkiat

XcodeGhost nos iPhones

Foi descoberto na semana passada um tipo de malware desenvolvido para iOS que conseguiu passar a segurança apertada relativa às aplicações que são submetidas na AppStore, colocando assim em risco vários milhões de utilizadores.

A Apple em declaração oficial já reconheceu a situação e já procedeu à remoção das aplicações infectadas sem dizer quantas ou quais é que se encontravam na AppStore.

Porque este é um assunto que levanta algumas dúvidas, deixamos agora aqui um FAQ com algumas pergunta e respostas sobre este malware para iOS.

1. O que é o XcodeGhost?

O XcodeGhost é um novo malware criado para afectar dispositivos que corram o iOS, tendo sido utilizado uma versão modificada do Xcode aquando do processo de criação da App.

2. Como é o XcodeGhost distribuído?

Uma versão do Xcode modificada com código malicioso foi introduzida num serviço de partilha de ficheiros do Baidu e descarregada por diversos programadores Chineses.

Desta forma esses programadores depois compilavam o software para iOS sem saberem que estavam a utilizar uma versão modificada do Xcode, o que permitiu que este malware conseguisse passar pelo processo de revisão da Apple para a aprovação das apps na AppStore.

3.Quais os dispositivos afectados?

Todos os modelos do iPhone, iPad e iPod Touch que corram uma versão do iOS compatível com as aplicações infectadas.

4. Quais as aplicações infectadas?

A empresa de segurança Palo Alto Networks, partilhou uma lista com mais de 50 aplicações infectadas, incluíndo WeChat, NetEase Cloud Music, WinZip, Didi Chuxing, Railway 12306, China Unicom Mobile Office.

5. Quantos utilizadores foram afectados?

Especula-se que cerca de 500 milhões de utilizadores possam ter descarregados uma das aplicações (ou actualizações) principalmente devido ao facto da app WeChat ser bastante popular na China.

6. Quais as versões do Xcode afetadas?

Qualquer versão da 6.1 à 6.4.

7. Quais os riscos que o XcodeGhost apresentam para o utilizador?

As aplicações infectadas permitem recolher informação sobre os dispositivos e depois, de forma encriptada, enviam esses dados para os servidores (C2) geridos pelos hackers. Os dados podem incluir:

      Hora e data actual
      Nome da aplicação infectada
      O bundle identifier da app
      Nome e tipo do dispositivo infectado
      Idioma e região do dispositivo
      UUID do dispositivo infectado
      Tipo de rede

Foi também descoberto que as aplicações infectadas podem receber comandos enviados pelos servidores geridos pelos hackers para alterar o comportamento da app:

      Criar uma janela a pedir usernames e passwords (phishing)
      Comprometer diversos URLs (hijacking) abrindo assim uma porta de possibilidades para explorar novas falhas no iOS.
      Ler e escrever dados no clipboard do iOS.
8. O XcodeGhost pode afectar utilizadores fora da China?

Sim. Algumas das apps infectadas estão disponíveis na AppStore de diversos países. A CamCard por exemplo é uma aplicação popular para ler e guardar cartões de visita que está disponível na AppStore dos EUA e outros países, enquanto que a WeChat apenas está disponível na China / países Asiáticos.

9. Porque é que os programadores descarregaram o Xcode modificado?

Devido ao tamanho do Xcode alguns programadores preferem descarregar o software disponível em mirrors em vez de o descarregarem dos servidores da Apple.

10. Como estão a Apple e os programadores a resolver o problema?

A Palo Alto Network diz que está a trabalhar em conjunto com a Apple para resolver o problema e para melhorar os processos de detecção, enquanto que os programadores actualizaram as suas aplicações para remover o malware.

A Apple emitiu um comunicado na reuters sobre este assunto: “We’ve removed the apps from the App Store that we know have been created with this counterfeit software. We are working with the developers to make sure they’re using the proper version of Xcode to rebuild their apps.”

11. Como me posso proteger?

Os utilizadores devem actualizar/remover imediatamente qualquer aplicação lista aqui. Alterar a password do iCloud ou quaisquer outras passswords introduzidas no seu dispositivo é também aconselhado.

Os programadores devem actualizar o Xcode para a versão 7 ou 7.1 beta e fazer o download apenas de fontes oficiais, neste caso os servidores da Apple.

Em Portugal os casos devem ser muito poucos, mas é sempre bom confirmar que sem alguma destas aplicações instaladas no seu dispositivo iOS.

Fonte: MacRumours

Fonte: Tudo sobre o virus do iPhone

App Store: Apple inicia limpeza devido a ataque de grande dimensão

Até ontem, apenas cinco apps infetadas chegaram à loja da Apple sem ser detetadas. Apple alerta programadores para não usarem ferramentas contrafeitas.

A Apple confirmou que a loja de apps do iPhone e do iPad foi alvo de um ataque de grandes proporções. A companhia reagiu ontem aos alertas lançados por várias empresas de segurança eletrónica dando início a um processo de “limpeza” da apps contaminadas por um código malicioso conhecido por XcodeGhost. O número de apps e utilizadores infetados não foi ainda revelado.

O nome do XcodeGhost explica em parte o método de disseminação deste malware: segundo referem os peritos, este código malicioso conseguiu pepetrar o primeiro ataque de grandes dimensões à loja da Apple através de uma “imitação” da plataforma Xcode, que costuma ser usada para as softwarehouses desenvolverem aplicações para os terminais da Apple.

O XcodeGhost terá começado a disseminar-se depois de vários programadores terem descarregado a versão maliciosa num servidor chinês, que teria como atrativo downloads mais rápidos que aqueles que, em média, costumam ser disponibilizados pelos servidores da Apple nos EUA.

De acordo com a BBC, as apps criadas com o XcodeGhost podem ser usadas para, remotamente e sem que os respetivos produtores saibam, desviar dados dos utilizadores, ou lançar falsos alertas que permitem obter passwords. Wechat, a app de aluguer de carros Didi Kuaidi, e o serviço de música da Netease estão entre as aplicações infetadas.

A Apple anunciou ontem que já começou a remover apps criadas com a versão contrafeita da Xcode (e que é conhecida por XcodeGhost). Mas essa é apenas uma parte da missão que a companhia tem pela frente: «Estamos a trabalhar com os programadores para garantir que estão a usar a versão adequada do Xcode para reconstruírem as apps», anunciou Christine Monaghan, porta-voz da Apple.

A Reuters revisitou o histórico de ataques à App Store e concluiu que, até à “invasão do XcodeGhost” apenas cinco apps tinham logrado passarem pelo escrutínio a que a Apple submete todas as aplicações antes de começar a disponibilizá-las na respetiva loja de software.

Entre os especialistas, há quem admita que outras lojas de aplicações poderão vir a ser alvo desta nova tendência de ataque que centra a mira nos programadores.

Fonte: App Store: Apple inicia limpeza devido a ataque de grande dimensão

5 mitos relacionados com baterias de dispositivos móveis

Todos nós nos habituámos a ouvir sugestões relacionadas com a utilização dada às baterias dossmartphones. Ainda hoje é comum ouvir a conversa da bateria que está viciada, quando simplesmente apresenta desgaste.

Mas existem outros mitos em volta das baterias e da sua utilização…

1. Não se deve utilizar o dispositivo enquanto a bateria está a carregar

Na verdade, os mitos surgem mas não são dadas grandes explicações quanto à sua possível credibilidade. Por que não utilizar o smartphone ou o tablet enquanto está a carregar?

Uma consequência dessa utilização será a de um carregamento mais lento, dependendo do tipo de tarefa que está a ser executada enquanto carrega. Outra das consequências, a que deve realmente ter algum cuidado, é do aquecimento do equipamento, já que está a ser alvo de um esforço extra. Como o calor é o maior inimigo da bateria, uma temperatura excessiva é prejudicial à bateria, não necessariamente apenas durante o período de carga.

2. Carregue sempre a bateria ao máximo!

Muitos dos mitos que ainda hoje se ouvem estão relacionados com as antigas baterias que vinham integradas nos nossos primeiros telemóveis, as baterias de níquel cádmio. Mas hoje em dia, os dispositivos estão, na sua grande maioria, equipados com baterias de iões ou polímeros de lítio, sendo muito mais modernas e com um desempenho muito mais eficiente.

Este tipo de baterias (que não vicia) tem uma vida útil que depende dos ciclos de carga, logo, quantos mais ciclos completar mais rapidamente irá degradar-se. Portanto, manter a bateria entre os 40% e os 80% será mais saudável para a vida útil da sua bateria. Mas se carregar a bateria ao máximo, ou se a deixar descarregar até níveis mais baixos (não inferiores a 10%), não irá notar, a curto prazo, perdas de autonomia significativas. Já uma descarga completa poderá inutilizar definitivamente uma bateria.

Leia também: O meu smartphone pode ficar a carregar durante toda a noite?

3. Não se pode deixar o smartphone a carregar durante toda a noite!

A verdade é que pode. Esta questão vai um pouco de encontro ao mito anterior. Se por um lado, para aumentar o tempo de vida de uma bateria, a sua carga deve oscilar entre os 40% e os 80%, por outro lado, na prática, são muito poucos os utilizadores que o fazem ou passaram a fazer. Deixar o equipamento ligado à electricidade muito tempo depois de atingir os 100% de carga não será um problema para a maioria deles.

Hoje em dia, todos os equipamentos estão preparados para que, assim que atinjam os 100% de carga, parar de receber energia, pelo que não serão alvo de sobrecarga.

No entanto, os fabricantes têm vindo a alertar para que os equipamentos que fiquem a carregar durante muitas horas seguidas não fiquem cobertos com cobertores, por exemplo, ou para que seja retirada a sua capa durante o processo, já que tendem a aquecer durante o processo de carga.

4. Não é necessário desligar nunca o seu dispositivo móvel

Já que desligá-lo poderá danificar a bateria.

Dar algum descanso à bateria ou ao próprio dispositivo não lhe fará mal nenhum. Pelo contrário. Esta acção poderá até ser benéfica para o dispositivo, já que irá “matar” algumas das acções em processo que tendem a diminuir o desempenho dos dispositivos. Pode também ajudar a que o dispositivo atinja uma temperatura mais baixa durante esse período.

5. Desligue Wi-Fi, o GPS e o Bluetooth para economizar bateria

Esta ideia pode não ser um total disparate, ou não ser propriamente um mito, dependendo do equipamento em utilização.

Em primeiro lugar, o Wi-Fi é um recurso relativamente económico, com pouca influência na autonomia. Já os dados móveis são mais consumidores de energia do que o Wi-Fi. Se está no escritório e só liga o Wi-Fi quando necessita mesmo de Internet no smartphone ou no tablet, a poupança de bateria que julga estar a fazer pode ser residual.

Quanto ao GPS, o dispositivo móvel, só o irá pedir localização quando realmente necessitar dela e, nesses casos, terá mais trabalho a ligá-lo manualmente, do que se o mantiver sempre ligado.

Os dispositivos móveis modernos já vêm todos equipados com Bluetooth 4.0, de muito baixo consumo de energia, pelo que as preocupações associadas à autonomia já não se colocam há muito.

Quais os hábitos que tem no tratamento das baterias?

Fonte: 5 mitos relacionados com baterias de dispositivos móveis

SVG Animation with GreenSock Animation Platform (GSAP)

GSAP brings vector images to life using scalable vector graphic (SVG) animations. You can animate a scene, develop HTML5 banner ads, improve project interfaces – the options are endless. My aim is to give you an introduction to GreenSock, the benefits of the platform and how to use it effectively.

To help illustrate how the platform works, I’ve embedded the development of an animation so you can see how we built it. I’ll then show you what the finished element turned out like. I’ve kept it basic on purpose but have provided links to further resources and information if you’re interested.

While you can use GSAP to animate any type of element, my focus is on using it with SVG images as there’s potential to create some awesome animations.

But first, a quick word on SVG images…

If you are unfamiliar with how SVG images and their properties, these two resources will help:

  • Jakob Jenkov has put together a great series of tutorials on his website. He is great at explaining SVG properties and including demos on how to use them.
  • Sara Soueidan writes in-depth articles on SVG for her website, making it easy to understand how it all works. She dives into the properties and provides great reference images.

On to Greensock.

Previously, you might’ve used Flash to animate for the web. But as support for Flash continues to die due to security flaws and lack of browser support, there’s a need for a worthy replacement. SVG has a range of benefits and with growingbrowser support, it makes good sense as a replacement for Flash.

One of the pain points with animating an SVG image is the inconsistencies in how browsers handle these types of images – in particular CSS transforms. Thankfully, this is where a tool such as GreenSock is handy. It solves browser inconsistencies and makes sure everything works as expected.

GSAP is a JavaScript animation library. It has a strong community, thorough documentation, large forums and plenty of demos to help educate you on how the platform works. GreenSock has multiple libraries that specialise in different areas and it’s worth browsing through the list to see what you can use.

Greensock’s performance in the browser is great. It gives you smooth transitions with the GSAP team claiming it’s “20x faster than jQuery” and “faster than CSS3 animations and transitions in many cases”.

If you want to test its performance for yourself, you can run a stress test on the GreenSock website. The test has two variables: the amount of dots animating around the screen; and the JavaScript library used to animate the dots. You can run the animation with different libraries and compare how they perform.

TweenLite is the core animation library for GSAP. It’s small and can be used alongside other GreenSock libraries. It will most likely be all you need for basic SVG animation. TweenMax is a larger library, containing Tweenlite, plus nine other GreenSock libraries. It provides a lot more functionality.

You can build a large animation without Tweenlite but you will find it hard to manage when you enter the editing phase.  This is because when you are animating elements one after another, you will need to set a duration and a delay for each element in your animation. As you tweak an element’s duration, your previously correct delays on other elements will now be too long or too short.  You’ll find yourself spending time re-tweaking delays so it still animates correctly.

GreenSock’s Timeline library comes in handy here, because it solves the above timing issues by completely removing the dependency for delays.  Each element in your stack waits for the previous elements to finish animating before it starts animating. Since the full animation runs in a cascading order you can reorder elements and change durations as you please.

Getting started

In the following examples, we will be using the TimelineMax library because it has more features. You could do these examples with TimelineLite though for a lighter weight version of the plugin.

The first thing to do is create a Timeline instance and store it as a variable. Your animations append to this new timeline. You are not restricted to only one timeline. If your animation was made up of lots of pieces you could createmultiple timelines for each piece and nest them under one master timeline.

var tl = new TimelineMax();

This line of code creates a timeline instance with a bunch of settings that are pre-configured. It’s possible to change the default behaviour, such as having the animation pause upon creation, or changing how many times the animation plays by passing in an object. To learn more about what you can do and how to do it at this point, refer to this documentation.

Animating elements in a timeline is straightforward. Below is an example of how to use the .to() method to change an element’s opacity to zero as it moves 100px on the x axis.

The tl variable we created in the previous step comes first and holds the timeline instance. Inside the to() method, the element to animate is passed in, along with the duration of the animation. After that, you can list anything you want to animate in a comma-separated list.

tl.to(element, duration, {
   x: 100,
   opacity: 0
});

Labels + timing.

Animations will be queued and played in whatever order you list them. They play one after the other, which is expected right? But what if we want to overlap animations, have a delay/pause between animations, or want to run multiple animations at the same time?

One way to achieve this is to add a string to the end of the method containing a time value.

The string will either need to include a += or -= followed by a duration. The += will add in the specified amount of time before it starts animating, creating a delay/pause effect between animations.

The -= will do the opposite, making the elements animation start early, creating an overlap effect between animations. In the first example below, the element waits 0.5 seconds before it starts animating. In the second example, the element starts animating 0.5 seconds before the first element finishes animating.

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "+=0.5");

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "-=0.5");

Another way of organising animated elements is to use labels. Labels group elements that you want to animate together in a string. You can name the label anything you choose. Elements with the same label will animate at the same time, rather than playing one after another. Labels can also be appended with += time and -= time if you want to add offsets to an element’s animation. Below are three examples of how you might implement labels in your timeline.

Example 1

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "myLabel");

Example 2

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "myLabel+=0.5");

Example 3

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "myLabel-=0.5");

Easing

Easing changes the rate of speed through an element’s animation. A linear ease will move an element at a constant speed from start to finish. An ease-out ease will start fast and slow down as the animation comes to an end. Adding the correct easing to your animations makes your animation more realistic and a lot better.

GreenSock offers a lot of easing types and offer a great visualiser tool on theirwebsite. If you want to learn more about easing and how it can be used, Ryan Brownhill wrote an article on crafting easing curves for user interfaces. It’s well worth a read and helps to further illustrate this concept.

You can also set the ease for an element’s animation. Below is an example of animating an element’s opacity and assigning a custom ease via the ease property.

tl.to(element, duration, {
    x: 100,
    opacity: 1,
    ease: SlowMo.ease.config(0.5, 0.7, false)
});

When you create a timeline instance, the setup with a default ease is Power1.easeOut. It’s possible to change the default ease with this line of code.

TimelineMax.defaultEase = add easing you want here;

Control

One of my favourite features of Timeline is that your animations are on a timeline and you can add controls. These controls pause, play, resume, reverse and restart the animation. You can build on this functionality to create some pretty cool interactive animations.

Chris Gannon, for example, created this demo to show you how you can scrub through an animation with your mouse. I also really like Adrian Parr’s demo on how to scrub through an animation using an on scroll event.

Key methods

If the information above is too dense for you, these are the fundamentals you need to get started. If nothing else, start attaching these methods to elements to see how they work. It’s also a great cheat sheet for when you’re getting started as these are methods you’ll find yourself using regularly. For an in-depth cheat sheet, check out the one Petr Tichy has put together here.

  • Set() is the equivalent of animating an element with a zero second duration. It alters an element’s appearance or position without any transition.
  • To() animates an element to a state.
  • FromTo() animates an element from one state to another state.
  • StaggerTo() animates a group of elements at the same time but with a staggered start time that you specify.
  • StagerFromTo() is a combination of the above fromTo() and staggerTo().

Helpful methods

In addition to the functionality I’ve provided in this article, I also wanted to briefly highlight three methods that I found helpful in Greensock.

  • Seek() is handy when it comes to tweaking and polishing your animation. It can be time consuming if watching the whole animation over and over. Seek takes either a time or label as its parameter. This means if you just want to view a part of your animation you can pass in a label and it will start from that point.
  • Pause() is great for inspecting what’s happening in your animation. It can be useful to chain this after a Seek call to see how things look.
  • Timescale() speeds up or slows down the overall timeline of your animation. Sometimes it can be hard to dissect an animation when it’s playing at a normal pace. Slowing it down gives you a better insight into how it’s fitting together. Timescale also comes in handy once you have built an animation and want to speed it up or slow it down without going through and tweaking the values.

The finished animation!

Putting all the above examples together, here is the finished animation I built using the tools and methods mentioned here. I encourage you to read the code and comments to see how it fits together.

View the animation on Codepen and play around with it in your browser. Don’t be scared of breaking it – go ahead and edit the code, tweak values and re-order events. Experimenting with the animation will improve your understanding of how it works. If you have any questions, feel free to add them to the comments below – I’m more than happy to try and help you out if I can.

Further resources

If you can’t get enough of GreenSock and want to read more about animating SVG images with it. Check out these links for more information.

Wrapping up

This article is meant to be an introduction to GSAP. I hope you’ve found it useful. Take these foundation ideas and create something simple or make it as intricate as you want. I’ve mentioned in a previous article that Codepen is a great source of inspiration and this is definitely the case for animations.

Here are some of my favourite GSAP animations. I recommend viewing the animations and reading the source code to see how different people create them. Viewing animations at a slower pace will help you get a better look at how it moves and fits together. As I mentioned earlier in the article, we can apply aTimescale to the timeline to slow it down.

After viewing the demos and learning how to animate using GreenSock, I hope you’re inspired to go off and make something of your own.

Post a link to your work in the comments, I’d love to see it. If you are thinking “I want to make something but I can’t think of anything to make”, check out theCodepen Creative Challenge.

It’s a growing community where users create pens around a theme. There are no prizes – it’s all for the fun of it. But it’s a great way to get inspired and to build something, share knowledge and be part of a community. It’s super-cool to see what others come up with.

Happy animating!

Allan gives us a run down of the GreenSock Animation platform and create an awesome animation for this blog article in the process. Check it out!

 

Fonte: SVG Animation with GreenSock Animation Platform (GSAP) | August

Want to learn JavaScript in 2015?

Uma excelente história de Vincent O que durante um ano, focou-se a aprender Javascript, e hoje trabalha nessa área.

Para contar esta história, Vincent utilizou o serviço Medium, website onde podemos contar as nossas histórias num layout simples e amigável.

This is a walk-through of the steps I personally took in a single year, to begin learning JavaScript. My goal was to be able to get a job…

Fonte: Want to learn JavaScript in 2015? — Medium

Tinderesque – building a Tinder-like interface with CSS animations and vanilla JS #justcode

Tinder is a very successful dating app, and one of its features is a way to say yes or no to prospective partners by swiping right or left or pressing a yes or no button. The interface is cards that drop when you press the buttons.

As with any successful interface, a lot of clones that mimick them happen very fast. One of those is FontFlame – a Tinder for Font Pairings. When I saw this one, I thought the animation isn’t right (it just moves to the right or left and fades, there’s no turning or popping up). I tried to fix the CSS animation to match more closely what Tinder is doing, but to my dismay I found out that whilst Fontflame uses CSS animations, they get over-ridden by jQuery ones. I contacted the author and offered my CSS animation to replace the current one.

Just for fun, I packed this up into a quick solution consisting of a CSS animation and some JavaScript to control the voting process.

I called it Tinderesque. You can see it in action, Get the code and read the instructionshow to use it on GitHub.

Here’s some explanations on how Tinderesque works.

THE TINDERESQUE ANIMATION

Animating the cards is no rocket science: we rotate the card after setting the transformation origin to the bottom of the card and shift it up a bit to get a “discard” effect.

First up, we need to define the HTML of the collection of cards we want to vote on. This should be pretty straight forward:

html

To achieve the animation effect we need to give the card we want to animate some dimensions and set its transform origin to its bottom:
.card {
  width: 150px;
  height: 200px;
  display: block;
  background: #666;
  transform-origin: 50% 99%;
}

This ensures that the card doesn’t get rotated around its centre but the bottom instead.

For the positive scenario, we rotate the card clockwise and push it up a bit to get the discard effect. This can be done using a rotate and translateY transformation. We also animate the opacity of the card from 1 to 0, effectively hiding it.

@keyframes yay {
  from {
    transform: rotate(0deg);
    opacity: 1;
  }
  to {
    transform: rotate(40deg) translateY(-80px);
    opacity: 0;
  }
}

For the negative use case, we rotate the card counter-clockwise:

@keyframes nope {
  from {
    transform: rotate(0deg);
    opacity: 1;
  }
  to {
    transform: rotate(-40deg) translateY(-80px);
    opacity: 0;
  }
}

We then trigger these animations by adding and removing classes on the parent elmement of the cards:

.cardcontainer.yes .card {
  animation: yay 0.7s ease-out;
}
.cardcontainer.nope .card {
  animation: nope 0.7s ease-out;
}

GOING THROUGH THE WHOLE CARD DECK

In order to go through the card deck two things must happen:

  • We need to animate the current card using the positive or negative animation
  • When the animation is finished, we need to remove the card from the document and show the next one.

By default, we hide all the cards in the deck. Only the one with the class of current is visible:

.list .card {
  display: none;
}
.list .current {
  display: block;
}

This means that we need to shift the class of current to the next card once this one has been approved or discared. But first, we need to trigger the animation. In order to achieve this, we need either a hover or some clever trickery with checkboxes in CSS. It is more extensible though to use JavaScript.

TRIGGERING THE ANIMATIONS

All we need to trigger the animations is adding an event handler attached to the buttons in the HTML. Depending on which button was pressed we add a yes or nope class to the parent element of the button – in this case, the cardcontainer DIV.

function animatecard(ev) {
  var t = ev.target;
  if (t.className === 'but-nope') {
    t.parentNode.classList.add('nope');
  }
  if (t.className === 'but-yay') {
    t.parentNode.classList.add('yes');
  }
}
document.body.addEventListener('click', animatecard);

We’re using event delegation here with a click handler on the body of the document. We can of course extend this to pointer or touch handlers to allow for touch events and simulating swipe gestures.

ACTING AFTER THE ANIMATION USING EVENTS

Our card has now been animated and is invisible, but it is still in the document and the next card isn’t visible yet. We need to remove the card and shift the current class to the next card in the deck.

Every CSS animation has an animationend event we can use for that. The event gives us the name of the event, which gives us the name of the class to remove.

function animationdone(ev) {
 
  // get the container
  var origin = ev.target.parentNode;
 
  // remove the appropriate class
  // depending on the animation name
  if (ev.animationName === 'yay') {
    origin.classList.remove('yes');
  }
  if (ev.animationName === 'nope') {
    origin.classList.remove('nope');
  }
 
  // if any of the card events have 
  // ended…
  if (ev.animationName === 'nope' ||
      ev.animationName === 'yay') {
 
  // remove the first card in the element
    origin.querySelector('.current').remove();
 
  // if there are no cards left, do nothing
    if (!origin.querySelector('.card')) {
      // no more cards left - 
      // TODO other functionality
    } else {
 
  // otherwise shift the 'current' class to 
  // the next card 
      origin.querySelector('.card').
        classList.add('current');
    }
  }
}
document.body.addEventListener(
  'animationend', animationdone
);

That’s more or less all we need to do. Except that Safari still hasn’t joined us in the year 2015. That’s why we need to repeat both the CSS animation definitions in our CSS with –webkit– prefixes and add an event handler for webkitAnimationEnd. I refuse to do so here, as this is depressing, but you can see it in the tinderesque source code.

EXTENDING THE FUNCTIONALITY USING CUSTOM EVENTS

The functionality now is pretty basic, which means we want to make it as easy as possible to extend it. The simplest way to do that is to add Custom Events that fire when things happen to our card deck. This is as easy as using this function:

function fireCustomEvent(name, payload) {
  var newevent = new CustomEvent(name, {
    detail: payload
  });
  document.body.dispatchEvent(newevent);
}

Custom events can get a payload – you can define what the listener gets as parameters. In the case of tinderesque, the animatecard function has been extended to send a reference to the button that was clicked, its container element (in case you have several decks) and a copy of the current card.

function animatecard(ev) {
  var t = ev.target;
  if (t.className === 'but-nope') {
    t.parentNode.classList.add('nope');
    fireCustomEvent('nopecard',
      {
        origin: t,
        container: t.parentNode,
        card: t.parentNode.querySelector('.card')
      }
    );
  }
  if (t.className === 'but-yay') {
    t.parentNode.classList.add('yes');
    fireCustomEvent('yepcard',
      {
        origin: t,
        container: t.parentNode,
        card: t.parentNode.querySelector('.card')
      }
    );
  }
}

This allows you to read the content of the card before it gets removed from the document.

var b = document.body;
b.addEventListener('nopecard', function(ev) {
  console.log(
    ev.detail.card,
    ev.detail.card.innerHTML
  );
});
b.addEventListener('yepcard', function(ev) {
  console.log(
    ev.detail.card,
    ev.detail.card.innerHTML
  );
});

Tinderesque also fires a custom event called deckempty when the last card got removed from the list. In the demo page this is used to re-stack the deck:

var b = document.body;
b.addEventListener('deckempty', function(ev) {
  var container = ev.detail.container;
  var list = container.querySelector('.cardlist');
  var out = '<li class="card current">#1</li>';
  for (var i = 2; i < 6; i++) {
    out += '<li class="card">#' + i + '</li>';
  }
  list.innerHTML = out;
});

This should get you well on the way to build your own Tinder-like interface. If I find the time, I will record a screencast doing exactly that.

CUTER – A QUICK DEMO USING TINDERESQUE

As a demo, I put together Cuter – a way to say yes or no to cute animal pictures and end up with a list of the ones you chose.
You can see it on YouTube:

https://www.youtube-nocookie.com/embed/6kvDBUTPV74?rel=0

Fonte: Tinderesque – building a Tinder-like interface with CSS animations and vanilla JS #justcode | Christian Heilmann