2014年12月18日 星期四

Laravel database 用法

其實也不一定要用laravel內的作法來建立資料表
但是用了好幾個好處,你可以快速的重建你的db,恢復,以及初始化資料表內容更彈性。

我用的到的也不多,就以下這幾句
php artisan migrate:make create_users_table//建立一支migrate檔
php artisan migrate//執行資料夾裡所有的migrate檔(建立
php artisan migrate:reset//執行資料夾裡所有的migrate檔(清除
php artisan db:seed//餵資料表資料

範例:以產生一個表的資料來說~
php artisan migrate:make create_users_table
會產生一支檔案 如:2014_12_17_213725_create_users_table.php
在/app/database/migrations/底下
裡面會有up跟down 2個function,
up是執行php artisan migrate時用的,down 是php artisan migrate:reset時用的
up裡寫上建表的script
// Creates the users table
        Schema::create('users', function($table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('username');
            $table->string('email');
            $table->string('password');
            $table->string('confirmation_code');
            $table->string('remember_token')->nullable();
            $table->boolean('confirmed')->default(false);
            $table->timestamps();
        });
down裡寫上清除的script
        Schema::drop('users');

接著執行 php artisan migrate就會建立新表了,執行php artisan migrate:reset又會清掉這張表

在/app/database/seeds/底下 有一支DatabaseSeeder.php
在裡面寫上要呼叫seed的檔案 如
Eloquent::unguard();

        // Add calls to Seeders here
        $this->call('UsersTableSeeder');

這支UsersTableSeeder放在同一層
class UsersTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->truncate();
        //DB::table('users')->delete();

        $users = array(
            array(
                'username'      => 'admin',
                'email'      => 'admin@test.org',
                'password'   => Hash::make('admin'),
                'confirmed'   => 1,
                'confirmation_code' => md5(microtime().Config::get('app.key')),
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            )
        );

        DB::table('users')->insert( $users );
    }

}
接著執行php artisan db:seed 就會餵資料進去了
使用DB::table('users')->truncate();會使auto_increment的值清空
DB::table('users')->delete();則不會。

//以下是unique跟foreign的用法
$table->unique(array('ad_id','ad_groups_id'));//將這2個鍵共設為unique
$table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade');//將本表的ad_id參考到ads表的id,當delete的時候。

參考資料來源
http://laravel.com/docs/4.2/migrations

2014年12月17日 星期三

Laravel 教學 db取值 分頁顯示

範例結果會長的像這樣↑

db的取值在laravel裡真的是一個神奇...
db取值在laravel有一個非常簡單的方法
在model資料夾裡開一個class,class的名稱是 Menu,就會對應到DB裡的 menus表,會把classname先轉小寫,再加一個s去對,所以你那個class就可以參考到menus的表了,也就是你db表一定要有個s在最後面才能用這招。class的寫法也很簡單 除了檔名跟class名要相同之外。
※但假如你用news(新聞)當model的話,這時候,就不能這麼幹了。因為他轉出來的表名稱會叫做news...不會叫newss
<?php
class Menu extends Eloquent {}
?>寫一句這個就行了

※laravel的流程通常是 routes->controllers->view

step1:如上所說,在model資料夾裡建一支Menu.php模型
<?php
class Menu extends Eloquent {}
?>


step2:在routes.php裡加上一行
Route::get('menu', 'HomeController@myMenu');

這的意思是用HomeController.php裡的myMenu這個function做事
沒有這支Controller就建一支(預設範本就有)

step3:開始寫public function myMenu()的code

到此為止,你已經可以使用Menu 這個class了,而你只是把他加入model的資料夾裡並且繼承了Eloquent
那你可以做什麼?
$menus = Menu::all();  //把db裡所有的資料倒出來!
View::make('menu', compact('menus'));//傳給menu的view,資料是menus(為什麼這裡是字串格式)

接著你在menu.php(這支放在view資料夾下)就可以直接參考到$menus這個變數了!!你可以簡單的用print_r把他們列出來。

那 怎麼做分頁顯示呢?
在api(http://laravel.com/api/4.2/)有一個叫paginate的方法,
你可以這樣用
$_menu=new Menu();
$menus=$_menu->paginate(2);//要怎麼預處理這個資料,order什麼的可以在分頁前做
View::make('menu', compact('menus'));
這樣就完成了
你會看到在頁面上,只會出現2筆資料,加上?page=2,就會出現第二頁的資料
<?php
foreach ($menus as $key => $value) {
echo $value['name']."</br>";
}
?>
{{ $menus->links() }}
在下面加上{{ $menus->links() }},還會出現頁次選單...(真的是很無微不至的laravel啊!)

2014年12月9日 星期二

windows底下裝virtualbox跑centos7 並安裝 laravel

.在virtual box上安裝CentOS-7.0-1406-x86_64-Minimal.iso
.安裝完後關掉虛擬機,重開登入後,先查ip,安裝#yum install net-tool,之後#ifconfig ,記下這台虛擬機的ip
.關掉虛擬機,並用VBoxManage.exe startvm "centos" --type headless 重新打開虛擬機 裡面的centos 是你虛擬機的名稱,這樣做可以讓虛擬機在背景跑。
.使用putty,連上虛擬機,安裝常用套件 yum install -y denyhosts rdate sudo wget man mlocate vim unzip lsof
.更新yum ,#yum update
.安裝nginx
#sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
#sudo yum install nginx
.把80 port打開,/sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
.啟動nginx #sudo systemctl start nginx.service
.試著連連看 ip 能不能打開nginx的welcome頁面
.#sudo systemctl enable nginx.service 加入開機執行
.安裝mysql db (安裝中的問題可以參考這篇 http://www.orztw.com/2014/02/install-mariadb-on-centos.html)
#sudo yum install mariadb-server mariadb
#sudo systemctl start mariadb
#sudo mysqladmin -u root password 'your-password'
.安裝php
#sudo yum install php php-mysql php-fpm

#sudo vi /etc/php.ini 把;cgi.fix_pathinfo=1的;拿掉後面改成0 cgi.fix_pathinfo=0

#sudo vi /etc/php-fpm.d/www.conf


修改listen = /var/run/php-fpm/php-fpm.sock

#sudo systemctl start php-fpm


#sudo systemctl enable php-fpm.service

修改nginx conf #sudo vi /etc/nginx/conf.d/default.conf


server {
    listen       80;
    server_name  server_domain_name_or_IP;

    root   /usr/share/nginx/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

#sudo systemctl restart nginx

web root在/usr/share/nginx/html/

安裝phpmyadmin(https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-phpmyadmin-with-nginx-on-a-centos-7-server)

sudo yum install epel-release(這裡面有mcrypt)

sudo yum install phpmyadmin

sudo ln -s /usr/share/phpMyAdmin /usr/share/nginx/html

sudo systemctl restart php-fpm

http://your/phpMyAdmin/

安裝laravel,先安裝composer

下載->#sudo curl -sS https://getcomposer.org/installer | sudo php

移到bin底下->#mv composer.phar /usr/local/bin/composer
try-> #composer

安裝laravel

#composer global require "laravel/installer=~1.1"

找個好目錄執行
composer create-project laravel/laravel your-project-name --prefer-dist

把新增的專案裡的

app/storage 設定可寫權限

進入專案,執行 #php artisan serve --host 你的ip --port 你的port

port如果設80會跟ngiinx相衝,關掉nginx的就可以了

之後就可以在外部連上去看結果了。


※假如你直接使用#php artisan serve,他應該是顯示 http://localhost:8000/
這在虛擬機裡是連的到的,但在外面就連不到了 因為你外面的localhost是指向127.0.0.1









2014年12月3日 星期三

AMS 5 install ON centsos 7 on virtualbox

※adobe media server 原名fms,5.0後改叫ams
1.安裝好virtualbox
2.下載centos7 iso,http://ftp.nsysu.edu.tw/CentOS/7.0.1406/isos/x86_64/CentOS-7.0-1406-x86_64-Minimal.iso
3.安裝centos7
4.設定網路橋接器 才可以拿到ip
5.centos Minimal版沒有ifconfig,要自已裝   #yum install net-tool,裝好之後拿到ip記下來。
6.安裝一些套件 yum install denyhosts rdate sudo wget man mlocate
7.更新套件 yum update
8.下載ams,解壓,安裝 #sudo ./installAMS
9.安裝途中設定的帳密要記下來 等等登入控制台會用到(4.5版會設80.1935的port,因為會跟apache相衝所以只設1935,但5.0版不會設80,所以免了)
10.安裝完後可以到 /opt/adobe/ams 執行 #./amsmgr adminserver start
11.接著把centos的port打開讓外面連的進來,我是直接把防火牆關了,#systemctl stop firewalld
12.done,接著你就能在外面的browser上輸入centos的ip,就可以看到ams的index畫面了~

※建議用putty操作比較快~
※執行vbox時,可以用VBoxManage.exe startvm "centos" --type headless 的指令,讓centos跑在背景,再用putty去操作。在vbox上的centos不好操作啊...
※fyi 實作上,防火牆不能關,但要開1935的rtmp協定 的 port
※要登入控制台 80跟1111都要開
#firewall-cmd --zone=public --add-port=1111/tcp --permanent
#firewall-cmd --reload




參考:
ams cmdline:
http://help.adobe.com/en_US/adobemediaserver/configadmin/WS5b3ccc516d4fbf351e63e3d119f29261b7-7fe7.2.3.html

補充下,安裝過程序號可以跳過,若已安裝nginx或apache,就不用選安裝apache,也不會讓你填80port,安裝完後把webroot資料夾移到你的 網頁根目錄 底下就行了

2014年10月23日 星期四

android multiplayer real-time

先當作筆記本。。。
1.主要照著這一份做 https://developers.google.com/games/services/console/enabling
2.然後下載sample https://github.com/playgameservices/android-basic-samples
解開裡面android-basic-samples-master\Scripts\make_eclipse_compat.cmd
我先執行這cmd,它會說要在android-basic-samples-master這個的目錄下執行,也就是cd到這個目錄,再用\Scripts\make_eclipse_compat.cmd 這樣去執行
產生一個eclipse_compat目錄。
我先在eclipse裡 import 這目錄裡的 button_click項目。當然會有error
接著再import BaseGameUtils 這個lib,這個lib要去reference google play service的lib(這一步可以參考http://developer.android.com/google/play-services/setup.html)
接著在BaseGameUtils 進屬性,在android的tab裡,把is library勾起來(代表這個project是個library)
接著就可以在button_click(不過import進來是叫mainactivity)的項目裡reference 到 BaseGameUtils 這個lib了~good!

其他在控制台上的設定 有一些值得講的
產生sha1的key,這個一開始是用eclipse的debug.keystore,所以在C:\Users\使用者名稱\.android底下。keytool就是在java的bin底下有。
執行keytool -exportcert -alias androiddebugkey -keystore debug.keystore -list -v
哦對了,debugkey的密碼是android
接著復製sha1那一行就好了。
然後在控制台裡把所有的設定設定到能夠發佈為止。(我任務亂建的!)

在eclipse發生一個問題
[2014-10-24 03:43:06 - Dex Loader] Unable to execute dex: Multiple dex files define Lcom/google/android/gms/R$attr;
[2014-10-24 03:43:06 - MainActivity] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/google/android/gms/R$attr;
[2014-10-24 03:43:31 - BaseGameUtils] R.java was removed! Recreating R.java!
說是gms下的r.java重覆定義了,我砍了button_click底下的不行,只好砍BaseGameUtils 底下的gms/r.java,嘛 也是過了。
後來就run起來了,不過還沒試多人連線的部份,明天拿另一台機器再來試。
感覺不錯 沒花幾個鐘。

2014年10月10日 星期五

ios推播教學&php push server

※程式碼的部份很少,相較於android實在是少的美妙極了
※整個過程分成3個部份,
1.開通註冊憑證 cert、p12、pem等等有的沒的...
2.在程序中加入程序拿到devicetoken
3.在push server上發送訊息
我就不貼原理了...反正我也沒什麼看

1.開通註冊憑證 cert、p12、pem等等有的沒的...
這部份參考別人寫的~
http://blog.maxkit.com.tw/2014/03/iospush-notification-providerjava-apns.html

2.在程序中加入程序拿到devicetoken
// Set Notification
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings 
     settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)      
categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
}

----------上面這三句就是發出通知,會回應該機器的devicetoken,回應有2個function,一個是成功(會帶著devicetoken,另一個失敗,會帶回error,如下)
- (void)application:(UIApplication *)app  didRegisterForRemoteNotificationsWithDeviceToken: (NSData *)newDeviceToken
{
    //將Device Token由NSData轉換為字串,本來是長的像 <2223 5556 1111 .... > 8組還幾組的數字
    
    NSString* deviceToken = [[[[[newDeviceToken description]
                                stringByReplacingOccurrencesOfString: @"<" withString: @""]
                               stringByReplacingOccurrencesOfString: @">" withString: @""]
                              stringByReplacingOccurrencesOfString: @" " withString: @""] retain];
    
    NSLog(@"%@",deviceToken);
   
    //取得device token!!
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError: (NSError *)err {
     NSLog(@"deviceToken error----%@",err);
//有錯誤訊息會在這裡顯示
}
3.在push server上發送訊息
可以參考這個網址,裡面有一些已有的工具,跟選擇,我最後是用php自已push訊息
http://kyleiossdk.blogspot.tw/2013/07/ios-apple-push-notification-service.html


php的code~

<?php

// Production mode
//$certificateFile = 'apns-dis.pem';
//$pushServer = 'ssl://gateway.push.apple.com:2195';
//$feedbackServer = 'ssl://feedback.push.apple.com:2196';

// Sandbox mode
$certificateFile = 'apns_dev.pem';
$pushServer = 'ssl://gateway.sandbox.push.apple.com:2195';
$feedbackServer = 'ssl://feedback.sandbox.push.apple.com:2196';

// push notification
$streamContext = stream_context_create();        

stream_context_set_option($streamContext, 'ssl', 'local_cert',dirname(__FILE__) . '\\' .$certificateFile);
//stream_context_set_option($streamContext, 'ssl', 'passphrase', $passphrase);
     
$fp = stream_socket_client(
    $pushServer,
    $error,
    $errorStr,
    100,
    STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT,
    $streamContext
);

// make payload
$payloadObject = array(
    'aps' => array(
        'alert' => 'Server Time:'.date('Y-m-d H:i:s'),
        'sound' => 'default',
        'badge' => 1
    ),
    'custom_key' => 'custom_value'
);
$payload = json_encode($payloadObject);

$deviceToken = '3952935260f9fb47ca9535f103d4fb6ceddf0fdc5935b8ee56aac876b91a316f';
$expire = time() + 3600;
$id = time();

if ($expire) {
    // Enhanced mode
    $binary  = pack('CNNnH*n', 1, $id, $expire, 32, $deviceToken, strlen($payload)).$payload;
} else {
    // Simple mode
    $binary  = pack('CnH*n', 0, 32, $deviceToken, strlen($payload)).$payload;
}
$result = fwrite($fp, $binary);
if($expire)echo "has expire";
echo "</br>";
if($binary)echo "has binary";
echo "</br>";
print_r($result);
fclose($fp);


?>

這裡會需要一個apns_dev.pem,
1.將 aps_development.cer 轉換為 aps_development.pem
1
openssl x509 -in aps_development.cer -inform DER -out aps_development.pem -outform PEM}
2. 將 private_key.p12 轉換為 private_key.pem
1
openssl pkcs12 -nocerts -out private_key.pem -in private_key.p12

3. 去除轉發密碼
1
openssl rsa -out private_key_noenc.pem -in private_key.pem

4. 合併 aps_development.pem 與 private_key_noenc.pem
1
cat aps_development.pem private_key_noenc.pem > apns_dev.pem

那你就得到apns_dev.pem了
(參考http://blog.yslin.tw/2011/07/apple-push-notification-provider-server.html)
這裡有幾個關鍵
//window下的寫法stream_context_set_option($streamContext, 'ssl', 'local_cert',dirname(__FILE__) . '\\' .$certificateFile);
//osx下的寫法
stream_context_set_option($streamContext, 'ssl', 'local_cert',$certificateFile);
也就是多加了個dirname(__FILE__) . '\\' .而已

php.ini 要打開
extension=php_openssl.dll

以及要打開ssl需要的模組~~~~~
但是做了这些,问题仍然不能解决,剩下的问题就是Apache需要开启ssl模块,通过查看Apache官方文档得知,使用ssl需要Apache开启三个支持模块分别是:
  1. mod_include
  2. mod_cgi
  3. mod_expires
都做完之後呢,請"關掉"apache",再打開。
直接按重啟是沒有效果的!!

對了,當然也有可能是你pem有問題
你可以在osx底下這樣測試你的pem是否正常
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert aps_development.pem -key apns_dev.pem


祝大家基本用法,使用愉快
//最近重用一次,看一下自已寫的文章,發現有一些備註應該要加上去。以下。
※在輸出p12檔時,有時候會發現沒辦法選p12,key圈上下方各有2部份的選單,上面要先選登入 ,下面選憑證,這樣有privatekey的憑證前面會多一個箭頭,可以展開,那這一個憑證就能輸出p12了。
當你在輸出p12的時候 所需要輸入的驗證碼,之後再組成pem時會用到。
使用ssl需要Apache开启三个支持模块,在哪開啟呢?以我windows上的例子是在C:\AppServ\Apache2.2\conf\httpd.conf裡去找到並把前面的#去掉,我的模組資料夾在C:\AppServ\Apache2.2\modules。可 以先檢查你有沒有相關的模組。

2014年6月1日 星期日

texturePacker command with cocos2d/windows

echo echo start > temp.bat
for /f %%i in ('dir/AD/B') do (
 echo TexturePacker --sheet %%i.png --data %%i.plist --format cocos2d --opt RGBA4444 C:/AppServ/www/project/sp/%%i >> temp.bat
 echo MOVE %%i.png E:\project\scripts\game_assets\sp >> temp.bat
 echo MOVE %%i.plist E:\project\scripts\game_assets\sp >> temp.bat
)
call temp.bat
pause
del temp.bat

參考之前寫的bat script
通常會將分散開來的原始圖按資料夾分好,並放在程式專案外的位置
將這個bat檔跟原始圖資料夾放在同一層,就能自動將各資料夾的圖包成sheet
並且移動到程式專案資料夾內。
敢腳command line跑起來速度不怎麼快呢...

2014年5月1日 星期四

quick cocos2dx 建立patch依照svn版本進行luajit encode

<?php
define("WORK_PATH", "E:\\");
define("USERNAME", "svn user name");
define("PASSWORD", "svn user password");
define("SVN_PATH", '"C:\Program Files\CollabNet\Subversion Client\svn.exe"');
define("ZIP_PATH", '"C:\Program Files\7-Zip\7z.exe"');
define('LUAJIT_BIN', '"C:\work\quick-cocos2d-x-2.2.1-rc\bin\win32\luajit.exe"');
define('SVN_CHECKOUT_PATH', 'http://127.0.0.1/myproject');

class patch
{
public function __construct(&$connect=NULL,&$IndexPDOConnect=NULL,&$share=NULL)
{
}

public function __destruct()
{
}

//釋出主版本
public function releaseVersion()
{
$this->makeDir("release");
$this->makeDir("release\\scripts");
$this->makeDir("release\\res");
$command=sprintf('xcopy %s %s /s/y',WORK_PATH."\\scripts","release\\scripts");
exec($command,$res,$r);
echo $command."result:".$r;
echo "</br>";
$command=sprintf('xcopy %s %s /s/y',WORK_PATH."\\res","release\\res");
exec($command,$res,$r);
echo $command."result:".$r;

$command=sprintf('dir %s /s/b',WORK_PATH."\\scripts");
exec($command,$res);
foreach($res as $key => $v)
{
$subName=$this->getSubName($v);
$_path=str_replace(WORK_PATH."\\", "", $v);
$_path="release\\".$_path;
if($subName=="lua")
{
$pathArr=explode("\\", $v);
$name=$pathArr[count($pathArr)-1];
if($name!="main.lua")
{
$command = sprintf('%s -b -s %s %s', LUAJIT_BIN, $_path,$_path);
echo "encrypt ".$_path;
exec($command,$res,$r);
if($r==1)
echo ">>>fail</br>";
else
echo ">>>success</br>";
}
}
}
}

//釋出子版本
public function releaseSubVersion()
{
$this->createPatchPath();
$res=$this->getSvnDiff();
foreach($res as $key => $v)
{
$arr=explode("    ", $v);
$act=$arr[0];
$path=$arr[1];
$_path=str_replace(WORK_PATH."\\", "", $path);
$_path=trim($_path);
$pathArr=explode("\\", $_path);
// print_r($pathArr);
if($act!="D")
$this->copyFile($path,$pathArr,$_path);
$this->encryptFile($path,$pathArr,$_path);
}
//zip files
$cmd=ZIP_PATH.' a -tzip '.$this->version.'.zip ./'.$this->version.'/*';
echo $cmd;
exec($cmd);
}
public function createPatchPath()
{
//$today = date("Ymdhis");
$this->makeDir(NOW_VERSION);
$this->version=NOW_VERSION;
}
public function getSvnDiff()
{
exec(SVN_PATH.' diff --summarize -r '.OLD_VERSION.':'.NOW_VERSION.' '.WORK_PATH.' --username '.USERNAME.' --password '.PASSWORD,$res);
return $res;
}
public function copyFile($sourcePath,$pathArr,$absPath)
{
$len=count($pathArr);
$path=$this->version;
for($i=0;$i<$len;$i++)
{
$str=$pathArr[$i];
if($this->checkIsFile($str))//is file
{
$checkoutPath=str_replace("\\", "/", $absPath);
$command = sprintf('%s export -r %s %s %s', SVN_PATH, NOW_VERSION, SVN_CHECKOUT_PATH.$checkoutPath,$path.'\\'.$str);
echo "export ".$str;
exec($command,$res,$r);
if($r==1)
echo ">>>fail</br>";
else
echo ">>>success</br>";
}
else//mk dir
{
$path.="\\".$str;
$this->makeDir($path);
}
}
}
public function encryptFile($sourcePath,$pathArr,$absPath)
{
$len=count($pathArr);
$path=$this->version;
for($i=0;$i<$len;$i++)
{
$str=$pathArr[$i];
if($this->checkIsFile($str))//is file
{
$subName=$this->getSubName($str);
//check is lua script
if($subName=="lua")
{
$command = sprintf('%s -b -s %s %s', LUAJIT_BIN, $path.'\\'.$str, $path.'\\'.$str);
echo "encrypt ".$str;
exec($command,$res,$r);
if($r==1)
echo ">>>fail</br>";
else
echo ">>>success</br>";
}
}
else
{
$path.="\\".$str;
}
}
}
public function checkIsFile($str)
{
return strrpos($str,'.');
}
public function getSubName($str)
{
$arr=explode(".", $str);
return $arr[1];
}
public function makeDir($path)
{
$b=file_exists($path);
if(!$b)
mkdir($path, 0777, true);
}
}
$patch=new patch();
if($_GET['old_ver']&&$_GET['now_ver'])
{
define("OLD_VERSION", $_GET['old_ver']);
define("NOW_VERSION", $_GET['now_ver']);//HEAD
$patch->releaseSubVersion();
}
else
{
$patch->releaseVersion();
}

?>

2014年3月6日 星期四

unity+lua memo

1.在lua中使用itween
local hash = System.Collections.Hashtable()
local Vector3=UnityEngine.Vector3(0, 1, 0)
hash:Add("position", Vector3)
hash:Add("time", 1)
hash:Add("oncompleteparams",partner1 )
hash:Add("oncomplete", function(arg) testLabel.setText("ok") partner1.play("Skill") end)
tween(partner1.ui, hash);
主要問題在回呼的部份
需要修改C:\Users\Administrator\Downloads\KLITest-13362\KLITest\Assets\iTween\iTween.cs
callback function底下 加入
else if(tweenArguments[callbackType].GetType() == typeof(LuaInterface.LuaFunction)) {
(tweenArguments[callbackType]as LuaInterface.LuaFunction).Call((object)tweenArguments[callbackType+"params"]);
}

2.在playmaker裡的action,可以右鍵點開來查看script或編輯,可以做一些code的參考。

3.要在lua裡咡取ngui的button事件,在button上加入Component->NGUI->Internal ->Event Listener,接著在lua中。(其中auto_btn是我button的id)
local ui=UnityEngine.GameObject.Find("auto_btn")
local textcomponent=ui:GetComponent("UIEventListener")
textcomponent.onClick = function() print("okokokok") end
這樣就可以了 太神奇了...為什麼神奇,因為c#的原碼是長這樣
void OnClick () { if (onClick != null) onClick(gameObject); }
我本來以為至少要改成
if (onClick
.GetType() == typeof(LuaInterface.LuaFunction) onClick.call(gameObject);
結果居然不用...(所以我寫code都用猜的嗎XD


2014年3月1日 星期六

mac ngx_lua openresty 教學-1 install and hello world

自從開始用cocos2dx 寫lua腳本後,就一直很想把server端也改用lua
最近也買了一台mac,今天花了一晚搞定了這個想法
nginx+lua模組,我一開始是使用homebrew安裝nginx,
接著再裝openresty,各種痛...
所以我後來就把homebrew裝的nginx uninstall掉了。。。

原因是openresty包裡有自帶nginx了

所以我們只需要安裝openresty就可以了~:)
1. 下載http://openresty.org/download/ngx_openresty-1.4.2.7.tar.gz
2. 解開ngx_openresty-1.4.2.7.tar.gz
3. git clone https://github.com/chaoslawful/lua-nginx-module.git
4. cd lua-nginx-module
5. git checkout -b websocket origin/websocket
6. cd ../ngx_openresty-1.4.2.7/bundle
7. rm -Rf ngx_lua-0.8.9
8. ln -s ../../lua-nginx-module ngx_lua-0.8.9
9. cd ..
10. ./configure \
--with-cc-opt="-I/usr/local/include” \
--with-ld-opt="-L/usr/local/lib” \
--with-luajit --prefix=/usr/local 
11. make
12. make install
安装完成后
cd ../
git clone https://github.com/agentzh/lua-resty-websocket.git
拷贝websocket到lualib目录下
cp -r lua-resty-websocket/lib/resty/websocket /usr/local/lualib/resty/

安裝完之後,就要啟動nginx , 不過發現執行nginx 會找不到指令
因為我們安裝的是
openresty,所以要使用openresty才行
openresty -h , 相當於nginx的使用方法

html資料夾在 /usr/local/Cellar/openresty/1.4.2.9/nginx/html
conf檔在 /etc/openresty/nginx.conf

接下來我們要在nginx.conf裡加上一些lua的設定
在http{裡加入
lua_package_path "/usr/local/lualib/resty/websocket/?.lua;;";

在server{裡加入
lua_code_cache off;   <---這一句可以使修改lua檔案時 可以直接更新 , 在nginx重啟時會出現警告提示

把listen 80;修改成
listen 80 default so_keeplive=on;

接著新增以下
location /luatest {
default_type 'text/plain';
content_by_lua_file /usr/local/Cellar/openresty/1.4.2.9/nginx/html/luatest.lua;
}

最後再建立一支luatest.lua 放到上面指定的位置上
該lua程式碼簡單寫上 ngx.say("hello lua") 就行了

最後打開browser 連上 localhost/luatest 就可以看到結果了:)