symfony老版本自主学习

刚刚入职新公司,使用的框架还是很老的symfony 1.4版本,这就很杯具了,只能慢慢学起来。官网只有高版本3.4和4.0的,好不容易找到1.4低版本的还都是英文版,算了就勉为其难的看看吧。先把链接地址发上,说不定有小伙伴也需要,之后便开始学吧。http://www.symfony-project.org/api/1_4/index.html

链接中第一个课程是Api,下面又细分了多个实用类:

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  <  sfComponent

下面来看看有哪些实用的方法:

    • 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,本身只有一个方法,其他方法都继承父类和`爷爷辈的`

string execute($request) 
Dispatches to the action defined by the 'action' parameter of the sfRequest object.
那么爷爷辈sfcomponent有哪些方法呢?

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

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

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

    • 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模型:

配置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.
generates four classes per table: An object of this class represents a single record of the jobeet_job table
then you could use it like this:

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

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

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 namePHP 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 namePHP 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 ; ?>
 


转载于:https://www.cnblogs.com/tangfeifei/p/9163410.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值