symfony老版本自主學習

剛剛入職新公司,使用的框架仍是很老的symfony 1.4版本,這就很杯具了,只能慢慢學起來。官網只有高版本3.4和4.0的,好不容易找到1.4低版本的還都是英文版,算了就勉爲其難的看看吧。先把連接地址發上,說不定有小夥伴也須要,以後便開始學吧。http://www.symfony-project.org/api/1_4/index.htmlphp

連接中第一個課程是Api,下面又細分了多個實用類:css

action

  • sfAction: sfAction executes all the logic for the current request.
  • sfActions: sfActions executes all the logic for the current request.
  • sfActionStack: sfActionStack keeps a list of all requested actions and provides accessor
  • sfActionStackEntry: sfActionStackEntry represents information relating to a single sfAction request during a single HTTP request.
  • sfComponent: sfComponent.
  • sfComponents: sfComponents.

 .sfAction  註解爲 執行當前請求的全部邏輯. 點進去以後發現其繼承了sf組件,而且是下一個sfactions的父類。 sfActions  <  sfAction  <  sfComponenthtml

下面來看看有哪些實用的方法:mysql

    • sfView::NONE renderComponent($moduleName, $componentName, $vars) 
      Appends the result of the given component execution to the response content.
    • sfView::NONE renderPartial($templateName, $vars) 
      Appends the result of the given partial execution to the response content.
    • sfView::NONE renderText($text) 
      Appends the given text to the response content and bypasses the built-in view system.
    • redirect($url, $statusCode) 
      Redirects current request to a new URL.
    • mixed getCredential() 
      Gets credentials the user must have to access this action.
    • string getComponent($moduleName, $componentName, $vars) 
      Returns the component rendered content.
    • string getPartial($templateName, $vars) 
      Returns the partial rendered content.
    • sfRoute getRoute() 
      Returns the current route for this request
    • string getTemplate() 
      Gets the name of the alternate template for this sfAction.
    • postExecute() 
      Execute an application defined process immediately after execution of this sfAction object.
    • preExecute() 
      Executes an application defined process prior to execution of this sfAction object.
    • forward404($message) 
      Forwards current action to the default 404 error action.
    • forward($module, $action) 
      Forwards current action to a new one (without browser redirection).

string getComponent($moduleName, $componentName, $vars) 
Returns the component rendered content.
  
再去看sfActions,自己只有一個方法,其餘方法都繼承父類和`爺爺輩的`
web

string execute($request) 
Dispatches to the action defined by the 'action' parameter of the sfRequest object.
那麼爺爺輩sfcomponent有哪些方法呢?
sql

mixed &($key) 
Gets a variable for the template.
api

mixed execute($request) 
Execute any application/business logic for this component.
瀏覽器

string generateUrl(, , ) 
Generates a URL for the given route and arguments.
cookie

    • string getActionName() 
      Gets the action name associated with this component.
        • sfContext getContext() 
          Retrieves the current application context.
        • sfController getController() 
          Retrieves the current sfController object.
          • string getModuleName() 
            Gets the module name associated with this component.
        • sfRequest getRequest() 
          Retrieves the current sfRequest object.
        • sfResponse getResponse() 
          Retrieves the current sfResponse object.
        • sfUser getUser() 
          Retrieves the current sfUser object. //獲取session對象,sfContext::getInstance->getUser();
      • mixed getVar($name) 
        Gets a variable set for the template.

 ORM模型:session

配置config.yml

alterable config options 

  • type: The column type (booleantinyintsmallintintegerbigintdoublefloatrealdecimalcharvarchar(size)longvarchardatetimetimestampblob, and clob)
  • required: Set it to true if you want the column to be required
  • index: Set it to true if you want to create an index for the column or to unique if you want a unique index to be created on the column.
  • primaryKey: Define a column as the primary key for the table.
  • foreignTableforeignReference: Define a column to be a foreign key to another table.
執行 php symfony propel:build --sql 會根據yml的生成對應的sql建表語句到目錄 data/sql/下
真實執行建表 則執行php symfony propel:insert-sql
$ php symfony propel:build --model  generates PHP files in the lib/model/ directory that can be used to interact with the database.lib/model/
generates four classes per table: An object of this class represents a single record of the  table
then you could use it like this:

jobeet_job
$job = new JobeetJob(); $job->setPosition('Web developer'); $job->save();   echo $job->getPosition();   $job->delete();

INIT DATA into table
create YAML files in the  directory and use the  task to load them into the database.data/fixtures/propel:data-load

LAYOUT:

it use decorator design pattern

$sfuser->setFlash() 
$sfuser->getFlash()
url_for('controller/action');   

eg:

'job/show?id='.$job->getId()

    url_for() helper converts this internal URI to a proper URL:

/job/show/id/1

include_stylesheets()  

Configuration Principles in symfony

For many symfony configuration files, the same setting can be defined at different levels:

  • The default configuration is located in the framework
  • The global configuration for the project (in config/)
  • The local configuration for an application (in apps/APP/config/)
  • The local configuration restricted to a module (inapps/APP/modules/MODULE/config/) 除了在這邊配置 引用的css,js 還能夠在templates中直接用
    <?php use_stylesheet('main.css') ?> 
    <?php user_helper('Text') ?>
    // apps/frontend/templates/layout.php
    <title><?php include_slot('title') ?></title>
    // apps/frontend/modules/job/templates/showSuccess.php
    <?php slot( 'title', sprintf('%s is looking for a %s', $job->getCompany(), $job->getPosition())) ?>
     

     

PDO:

$ php symfony configure:database "mysql:host=localhost;dbname=jobeet" root mYsEcret

 [need three arguments]:  [ the PDO DSN, the username, and the password]

 

Project category:

apps/
  frontend/
    modules/
      job/
        actions/
          actions.class.php
        templates/
          indexSuccess.php

 首頁方法:

  public function executeIndex(sfWebRequest $request)

{
/** 設置變量的2種方式 ** / $this->foo = 'bar'; $this->bar = array('bar', 'baz');

  $this->setVar('foo','bar'); }

The Request and the Response

The Request

The sfWebRequest class wraps the $_SERVER$_COOKIE$_GET$_POST, and $_FILES PHP global arrays:

Method name PHP equivalent
getMethod() $_SERVER['REQUEST_METHOD']
getUri() $_SERVER['REQUEST_URI']
getReferer() $_SERVER['HTTP_REFERER']
getHost() $_SERVER['HTTP_HOST']
getLanguages() $_SERVER['HTTP_ACCEPT_LANGUAGE']
getCharsets() $_SERVER['HTTP_ACCEPT_CHARSET']
isXmlHttpRequest() $_SERVER['X_REQUESTED_WITH'] == 'XMLHttpRequest'
getHttpHeader() $_SERVER
getCookie() $_COOKIE
isSecure() $_SERVER['HTTPS']
getFiles() $_FILES
getGetParameter() $_GET
getPostParameter() $_POST
getUrlParameter() $_SERVER['PATH_INFO']
getRemoteAddress() $_SERVER['REMOTE_ADDR']

 

The Response

The sfWebResponse class wraps the header() and setrawcookie() PHP methods:

Method name PHP equivalent
setCookie() setrawcookie()
setStatusCode() header()
setHttpHeader() header()
setContentType() header()
addVaryHttpHeader() header()
addCacheControlHttpHeader() header()

 

 

URLs

'job/show?id='.$job->getId()

   The url_for() helper converts this internal URI to a proper URL: change to this format => MODULE/ACTION?key=value&key_1=value_1&...

/job/show/id/1

Routing Configuration

# apps/frontend/config/routing.yml
homepage:
  url:   /
  param: { module: default, action: index }
 
default_index:
  url:   /:module
  param: { action: index }
 
default:
  url:   /:module/:action/*

從上到下依次匹配,第一個知足條件就結束。
/job 匹配到了 default_index
/job/show/id/1 匹配到default
url_for('job/show?id='.$job->getId()) is equivalent to url_for('@default?module=job&action=show&id='.$job->getId())
but letter is faster because it has recognized routing ,parse the route parameters.

you can also directly use explicit route like below
# apps/frontend/config/routing.yml homepage: url: / param: { module: job, action: index }
<!-- apps/frontend/templates/layout.php -->
<h1>
  <a href="<?php echo url_for('homepage') ?>"> =>  job/index
    <img src="/legacy/images/logo.jpg" alt="Jobeet Job Board" /> </a> </h1>
anohter format will parse many parameter: 因此傳參時也須要給多個參數,否則匹配不上,同時能夠指定部分參數的格式
job_show_user:
  url:   /job/:company/:location/:id/:position
class:sfRequestRoute //指定路由類
param: { module: job, action: show }
requirements: id: \d+
sf_method: [get] //限制請求方式
 

Object Route Class

 

Route Class

routing.yml is internally converted to an object of class sfRoute

 

link_to() helper which generates an <a> tag: 

<a href="/job/sensio-labs/paris-france/1/web-developer">Web Developer</a>

   <?php echo link_to('Web Developer','/job/sensio-labs/paris-france/1/web-developer',[id=>1]) ?>

redirect => 瀏覽器跳轉url變動   forward =>頁面跳轉url不變化

 

SfView

默認視圖調用 sfView::SUCCESS

# 將調用indexSuccess.php模板
public function executeIndex()
{
  return sfView::SUCCESS;
}
# 將調用listSuccess.php模板
public function executeList()
{
}
# symfony將查找actionNameError.php模板
return sfView::ERROR;
# symfony將查找actionNameMyResult.php模板
return 'MyResult' ; or  $this->setTemplate('myCustomTemplate');
#不返回視圖
return sfView::NONE;

發送空的響應但包含定義的頭信息(特別是X-JSON頭),定義頭經過sfResponse對象,而且放回sfView::HEADER_ONLY常量:
public function executeRefresh()
{
  $output = '<"title","My basic letter"],["name","Mr Brown">' ;
  $this ->getResponse()->setHttpHeader( "X-JSON" , '(' . $output . ')' );
  return sfView::HEADER_ONLY;
}
$this->forward('Module','Action');內部跳轉,url連接不變化
$this->redirect(''); 外部跳轉,url也變化

class mymoduleActions extends sfActions
{
  public function preExecute()
  {
   // 這裏的代碼在全部動做調用以前執行
   ...
  }
  public function executeIndex()
  {
   ...
  }
  public function executeList()
  {
   ...
   $this ->myCustomMethod(); // 調用自定義的方法
  }
  public function postExecute()
  {
   // 這裏的代碼會在每一個動做結束後執行
   ...
  }
  protected function myCustomMethod()
  {
   // 添加本身的方法,雖然他們沒有以execute開頭
   // 在這裏,最好將方法定義爲protected(保護的)或者private(私有的)
   ...
  }
 
class mymoduleActions extends sfActions
{
  public function executeUpload()
  {
   if ( $this ->getRequest()->hasFiles())
   {
    foreach ( $this ->getRequest()->getFileNames() as $fileName )
    {
     $fileSize = $this ->getRequest()->getFileSize( $fileName );
     $fileType = $this ->getRequest()->getFileType( $fileName );
     $fileError = $this ->getRequest()->hasFileError( $fileName );
     $uploadDir = sfConfig::get( 'sf_upload_dir' );
     $this ->getRequest()->moveFile( 'file' , $uploadDir . '/' . $fileName );
    }
   }
  }
}
}
 
 
class mymoduleActions extends sfActions
{
  public function executeRemoveNickname()
  {
   $this ->getUser()->getAttributeHolder()->remove( 'nickname' );  //session 屬性倉庫清除data
  }
  public function executeCleanup()
  {
   $this ->getUser()->getAttributeHolder()->clear();
  }
}
模版中的用法:

 Hello, <?php echo $sf_user->getAttribute('nickname') ?>

 

Flash屬性是一種短命屬性,他會在最近的一次請求後消失,這樣能夠保持你的Session清潔

$this->setFlash('attrib', $value);

$value = $this->getFlash('attrib');

<?php if ( $sf_flash ->has( 'attrib' )): ?>
  <?php echo $sf_flash ->get( 'attrib' ) ?>
<?php endif ; ?>
相關文章
相關標籤/搜索