quinta-feira, 8 de dezembro de 2016

How to use Blade Without Laravel

Blade is so nice, but sometimes you have to work on legacy projects or with frameworks not friendly. So, looking at the web i found the windwalker that until now is doing great. So, here i'll show a basic step-by-step to use Blade without Laravel. First, we'll configure composer, so install composer if you don't have it.
Create the composer.json:
 {  
      "autoload":{  
           "psr-4":{  
                "App\\": "app",  
                "Windwalker\\": "vendor/windwalker"  
           }  
      },  
      "require": {  
     "windwalker/renderer": "2.*",  
     "illuminate/view": "4.*"  
   }  
 }  
Here, i set the namespace for my work environment: App and Windwalker to use in my initial load. The require pull the libs. Now composer install(if you did not have) && composer update(if you updated) && composer auto-load
Create a folder init and write blade.php:
 <?php   
 use Windwalker\Renderer\BladeRenderer;  
 $paths = array('./view');  
 $renderer = new BladeRenderer($paths, array('cache_path' => './cache'));  
Set the path to your view folder and to a cache folder.
 <?php  
 require 'vendor/autoload.php';  
 require 'init/blade.php';  
 $data = ['title' => 'Nice!'];  
 $html = $renderer->render('index', $data);  
 echo $html;  

Create index.blade.php file in view folder.
 @section('title')  
      @if( isset($title) )  
           {{ $title }}  
      @else  
           Without Title  
      @endif       
 @stop  
 <html>  
 <head>  
 <title>@yield('title')</title>  
 </head>  
 <body>  
 <p>Body</p>  
 @include('footer')  
 </body>  
 </html>  
I created a footer.blade.php file to show the include.
Check this on: Github
References:
http://asika.windspeaker.co/post/3975-use-blade-template-engine-outside-laravel
https://packagist.org/packages/philo/laravel-blade

quarta-feira, 23 de novembro de 2016

Using Intermediate Language Disassembler

Sometimes, with me very often, we do some “nonsense”. Some code analysis tool may help us. If you’re not very confident you could use Intermediate Language Disassembler or ildasm.exe. Here i present some little tips using Intermediate Language Disassembler. First make sure you have VS, and open vs native tools. With vs native tools open enter ildasm. Now we’ll make a basic program with C#.
 class Program  
   {  
     static void Main(string[] args)  
     {  
       Console.WriteLine("ok");  
     }  
   }  
Now you can build and after, open ildasm File > open and select your .exe and double click in main method, you will see this:
 .method private hidebysig static void Main(string[] args) cil managed  
 {  
  .entrypoint  
  // Code size    13 (0xd)  
  .maxstack 8  
  IL_0000: nop  
  IL_0001: ldstr   "ok"  
  IL_0006: call    void [mscorlib]System.Console::WriteLine(string)  
  IL_000b: nop  
  IL_000c: ret  
 } // end of method Program::Main  
So, no big deal, we have the string literal stored opcode following call to the WriteLine. Now we’ll do a potentially dangerous operation, we’ll write a method that expects an object, following we’ll pass a double. This will generate a box operation, so:
 class Program  
   {  
     static void Main(string[] args)  
     {  
       Console.WriteLine("ok");  
       double wrong = 2.3;  
       pass(wrong);  
     }  
     static void pass(Object wrong)  
     {  
       Console.WriteLine(wrong);  
     }  
   }  
Now we build and following we use ildasm:
 .method private hidebysig static void Main(string[] args) cil managed  
 {  
  .entrypoint  
  // Code size    35 (0x23)  
  .maxstack 1  
  .locals init ([0] float64 wrong)  
  IL_0000: nop  
  IL_0001: ldstr   "ok"  
  IL_0006: call    void [mscorlib]System.Console::WriteLine(string)  
  IL_000b: nop  
  IL_000c: ldc.r8   2.2999999999999998  
  IL_0015: stloc.0  
  IL_0016: ldloc.0  
  IL_0017: box    [mscorlib]System.Double  
  IL_001c: call    void Generics.Program::pass(object)  
  IL_0021: nop  
  IL_0022: ret  
 } // end of method Program::Main  
Now, we can see some nice things. First, we “discover” that our double is called float64, the 2.3 value(could not be different) is put as 2.2999999999999998 with the ldc.r8 opcode that pushes the value to the evaluation stack. Following we have our potentially Dracula: in the IL_0017 we have our box.
In MSDN:
In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally. For more information, see Performance.

https://msdn.microsoft.com/en-us/library/yz2be5wk(v=vs.80).aspx

References:
https://msdn.microsoft.com/en-us/library/yz2be5wk(v=vs.80).aspx
https://app.pluralsight.com/library/courses/csharp-generics/table-of-contents

segunda-feira, 7 de novembro de 2016

Testing Repository with Laravel and Mockery

I was reading the awesome Taylor Otwell’s Book - Laravel From Apprentice To Artisan- https://leanpub.com/laravel and i’ll show some nice examples mixed with some code i did. So, let’s do dependency Injection:
 namespace App\Contracts;  
 interface ProductRepositoryInterface{  
      public function all();  
 }  
Now our Repo:
 <?php  
 namespace App\Repositories;  
 use App\Contracts\ProductRepositoryInterface;  
 use App\Product;  
 class ProductRepository implements ProductRepositoryInterface{  
      public function all(){  
           return Product::all()->toArray();  
      }  
 }  
Now we can use the Repo:
 namespace App\Http\Controllers;  
 use Illuminate\Http\Request;  
 use App\Http\Requests;  
 use App\Product;  
 use App\Contracts\ProductRepositoryInterface;  
 use Response;  
 class ProductController extends Controller  
 {  
      public function __construct(ProductRepositoryInterface $products){  
           $this->products = $products;  
      }  
      public function index(){  
           $products = $this->products->all();  
           return view('products.index', compact('products'));  
      }  
 }  
Don’t forget the Routes!!!! Now we can test:
 <?php  
 use App\Product;  
 use Illuminate\Foundation\Testing\WithoutMiddleware;  
 use Illuminate\Foundation\Testing\DatabaseMigrations;  
 use Illuminate\Foundation\Testing\DatabaseTransactions;  
 class ExampleTest extends TestCase  
 {  
   use DatabaseTransactions;  
   public function tearDown(){  
     Mockery::close();  
   }  
   public function testIndexActionBindsProductsFromRepository(){  
     $mock = Mockery::mock('App\Contracts\ProductRepositoryInterface');  
     $mock->shouldReceive('all')->once()->andReturn(['lol', 'kk']);  
     App::instance('App\Contracts\ProductRepositoryInterface', $mock);  
     $response = $this->action('GET', 'ProductController@index');  
     $this->assertResponseOk();  
     $this->assertViewHas('products', ['lol', 'kk']);  
   }  
 }  
We use DatabaseTransactions; to rollback the changes. In the test we mock our Interface and arrange telling that it gonna receive a call for all() and return array [‘lol’, ‘kk’]. Using App::instance we register that in the execution when the interface is requested it will throw our mock. With this we simulate a GET request with action(). The assertion is ok and our view has the array. Now we’ll use the factory, in database > factories register the following:
 $factory->define(App\Product::class, function (Faker\Generator $faker) {  
   return [  
     'title' => $faker->sentence  
   ];  
 });  
We used only the title for simplicity. Now we can do the following test:
 public function testProductsCreationAndJsonList(){  
     factory(Product::class, 3)->create();  
     $response = $this->action('GET', 'ProductController@getProducts');  
     $this->assertResponseStatus(200);  
 }  
With create() we insert 3 products in the database. With the action we simulate the request and assert the status. Now we put the getProducts():
 public function getProducts(){  
           $products = $this->products->all();  
           //refactoring this -> next POST!!!! we gonna make a class to implement the return and extend  
           if (empty($products)){  
                $arrResponse = ['error' => ['message' => 'No Product found', 'code' => 'Internal Code']];  
                return Response::json($arrResponse, 404);  
           }  
           return Response::json(['data' => $products], 200);  
      }  
In the next post we will refactor getProducts and extract a class. TY References: https://leanpub.com/laravel
https://laracasts.com/series/phpunit-testing-in-laravel
https://laravel.com/docs/5.2/mocking

quinta-feira, 29 de setembro de 2016

JS all the way

Angular, Node, Electron, Ionic, JS all the way. But, are these things good and proper for all kinds of apps? Of course, the answer is no, but i’m using these things a lot and these guys are saving me with portability and awesome apis. Use with caution. Is this JS domination or JS doom?

quarta-feira, 28 de setembro de 2016

A Drink App with Ionic

I'm developing a drink game with Ionic. In College, I played this so many times and now i've decided to make an app. The new version[v3] has support for english and Friends Mode. New things coming. Unfortunately, at the moment only Android is available and with apk. I'll try to put this on Play Store and App Store. The v3 can be downloaded at :

https://drive.google.com/file/d/0B-MDes2BI4gZVWNhTDFXSEhZcEk/view?usp=sharing

The v4 can be downloaded at :

https://drive.google.com/file/d/0B-MDes2BI4gZQTRELVFBcmFiOWs/view?usp=sharing



The v2 in Amazon Store:

https://www.amazon.com/Aldo-Lemos-drunkMe/dp/B01M197ROO/ref=sr_1_1?s=mobile-apps&ie=UTF8&qid=1475109747&sr=1-1&keywords=drunkme

terça-feira, 27 de setembro de 2016

Um App Simples com Ionic - Link para APK

Um dia desses brincando com o framework Ionic, resolvi criar um app baseado no jogo que muitos chamam de apertadinho, acabei não achando um jogo parecido para android ou ios. Um jogo simples, que consiste em escolher 3 números tal que o terceiro está entre os dois primeiros. Quem acertar o número escolhido pelo app ou por um jogador bebe ou paga o mico. Se o número escolhido durante a rodada não permite o próximo jogador escolher, quem pensou no número inicial tem que beber. A melhor forma de aprender é jogando, então baixe o apk e instale pelo link abaixo(não esqueça de permitir arquivos de fora da google play). Infelizmente, por enquanto só usuários de Android terão acesso, mas se poucos bugs forem achados faço um esforço para subir o app para Ios e Windows e fazer uma integração com facebook para você mostrar aos seus amigos que tem sorte. Por enquanto o app ficará no link abaixo e na amazon store.


Link para Amazon Store: https://www.amazon.com/Aldo-Lemos-drunkMe/dp/B01M197ROO/ref=sr_1_1?s=mobile-apps&ie=UTF8&qid=1475064324&sr=1-1&keywords=drunkme


Link direto: https://drive.google.com/open?id=0B-MDes2BI4gZRTNYSDJLWmh2OEE