Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > OOP
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

 
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 07-04-2011
elarys elarys is offline
Miembro
 
Registrado: abr 2007
Posts: 94
Poder: 18
elarys Va por buen camino
Pasar mi clase a una clase de 3 capas o lo mas parecido

Aqui mi clase, para manejar una tabla de una base de datos, que la tengo en sql server, pero que pasa, ahora me quiero pasar a mysql o firebird y necesito cambiar mi clase, supuestamente la tengo facil tengo que cambiar mis TADOConnection y TADOQuery, por los componentes que vaya a usar para conectarme a la misma tabla pero ahora en distinta base de datos.
Como seria en tres capaz, esta es practicamente la parte de acceso a datos, pero necesito optimizarla porque cada vez que la interfaz pide datos estoy creando una nueva conexion "me ayudan a optimizarla alguna linea a seguir"

Todavia no entiendo bien cual seria la capa de logica de negocios

Mi clase
Código Delphi [-]
unit Documents;

interface

uses
  SysUtils, Classes, Forms, DB, ADODB, Base;

type
  TDocuments = class (TPersistent)
  protected
    FModified:boolean;
    FId_Document:integer;
    FFormat_Code:string;
    FDescription:string;

  private
    procedure SetRecord(qryTMP:TADOQuery);
    procedure SetMaxRecord(qryTMP:TADOQuery);
    procedure SetParameter;
    procedure SaveModified;
    procedure SaveNew;

    procedure SetId_Document(val:integer);
    procedure SetFormat_Code(val:string);
    procedure SetDescription(val:string);    
    function GetId_Document:integer;
    function GetFormat_Code:string;
    function GetDescription:string;

  public
    strSQL:string;
    claDatos:TDatos;
    qryTMP:TADOQuery;
    procedure SaveData(new:boolean);
    procedure SetMax;
    procedure Delete;

    property Id_Document : integer read GetId_Document write SetId_Document;
    property Format_Code : string read GetFormat_Code write SetFormat_Code;
    property Description : string read GetDescription write SetDescription;

    function FindByPrimaryKey(pk:integer):TDocuments;

  end;

  TDocumentsList = class (TPersistent)
  private
    FDocuments:TList;
    strSQL:string;
    qryTMP:TADOQuery;
  protected
    function GetItems(index:integer): TDocuments;
  public
    constructor Create;
    procedure Add(item:TDocuments);
    procedure Delete(index:integer);
    function GetCount:integer;
    property Count:integer read GetCount;
    property Items[index:integer]: TDocuments read GetItems;
    procedure GetAll;
    procedure Busqueda(TDocu:TDocuments);
  end;

  function ConsultaSQL(strSQL: string):TADOQuery;
  function EjecutarSQL(strSQL: string; claDatos:TDatos):TADOQuery;

{************************************ TDocuments *****************************************}

implementation

procedure TDocuments.SetParameter;
begin
  claDatos := TDatos.Create;
  claDatos.Clear;
  claDatos.AddParam('PId_Document',ftInteger,FId_Document);
  claDatos.AddParam('PFormat_Code',ftString,FFormat_Code);
  claDatos.AddParam('PDescription',ftString,FDescription);
end;

procedure TDocuments.SaveModified;
begin
  SetParameter;
  
  strSQL :=
    ' UPDATE Documents SET'+
    ' Format_Code=:PFormat_Code,'+
    ' Description=:PDescription,'+
    ' WHERE Id_Document=:PId_Document';

  EjecutarSQL(strSQL, claDatos);
end;

procedure TDocuments.SaveNew;
begin
  SetParameter;
  
  strSQL :=
    ' INSERT INTO Documents VALUES ('+
    ' :PId_Document,'+
    ' :PFormat_Code,'+
    ' :PDescription)';

  EjecutarSQL(strSQL, claDatos);
end;

procedure TDocuments.Delete;
begin
  claDatos := TDatos.Create;
  claDatos.AddParam('PId_Document',ftInteger,FId_Document);

  strSQL :=
    ' DELETE * FROM Documents'+
    ' WHERE Id_Document=:PId_Document';

  EjecutarSQL(strSQL, claDatos);
  Self.Free;
end;

function TDocuments.FindByPrimaryKey(pk:integer): TDocuments;
begin
  strSQL := 'SELECT * FROM Documents WHERE Id_Document ='+IntToStr(pk);
  ConsultaSQL(strSQL);
  SetRecord(qryTMP);
  result := Self;
end;

procedure TDocuments.SetRecord(qryTMP:TADOQuery);
begin
  Self.FId_Document := qryTMP.Fields.FieldByName('Id_Document').AsInteger;
  Self.FFormat_Code := qryTMP.Fields.FieldByName('Format_Code').AsString;
  Self.FDescription := qryTMP.Fields.FieldByName('Description').AsString;
end;

procedure TDocuments.SetMaxRecord(qryTMP:TADOQuery);
begin
  Self.FId_Document := qryTMP.Fields.FieldByName('maxnum').AsInteger + 1;
end;

procedure TDocuments.SaveData(new:boolean);
begin
  claDatos := TDatos.Create;
  if new then
    SaveNew
  else
    SaveModified;
    
  FModified := False;
end;

procedure TDocuments.SetMax;
begin
  strSQL := 'SELECT MAX(Id_Document) AS maxnum FROM Documents';
  qryTMP := ConsultaSQL(strSQL);
  SetMaxRecord(qryTMP);
end;

procedure TDocuments.SetId_Document(val:integer);
begin
  if FId_Document <> val then
  begin
    FId_Document := val;
    FModified := True
  end;
end;

function TDocuments.GetId_Document:integer;
begin
  Result := FId_Document;
end;

procedure TDocuments.SetFormat_Code(val:string);
begin
  if FFormat_Code <> val then
  begin
    FFormat_Code := val;
    FModified := True;
  end;
end;

function TDocuments.GetFormat_Code:string;
begin
  Result := FFormat_Code;
end;

procedure TDocuments.SetDescription(val:string);
begin
  if FDescription <> val then
  begin
    FDescription := val;
    FModified := True;
  end;
end;

function TDocuments.GetDescription:string;
begin
  Result := FDescription;
end;

{************************** TDocumentsList ***************************}

procedure TDocumentsList.Add(item:TDocuments);
begin
  FDocuments.Add(item);
end;

constructor TDocumentsList.Create;
begin
  FDocuments := TList.Create;
end;

procedure TDocumentsList.Delete(index:integer);
begin
  FDocuments.Delete(index);
end;

procedure TDocumentsList.GetAll;
var
  Documents:TDocuments;
  i:integer;
begin
  strSQL := ' SELECT * FROM Documents';
  ConsultaSQL(strSQL);
  qryTMP.First;
  for i := 0 to qryTMP.RecordCount - 1 do
  begin
    Documents := TDocuments.Create;
    Documents.SetRecord(qryTMP);
    FDocuments.Add(Documents);
    qryTMP.Next;
  end;
  qryTMP.Free;
end;

function TDocumentsList.GetCount:integer;
begin
  Result := FDocuments.Count;
end;

function TDocumentsList.GetItems(index:integer):TDocuments;
begin
  Result := TDocuments(FDocuments[index]);
end;

procedure TDocumentsList.Busqueda(TDocu:TDocuments);
var
  sql:string;
  Documents:TDocuments;
  i:integer;
begin
  if not assigned (TDocu) then
    TDocu := TDocuments.Create;

  if TDocu.FId_Document > 0 then
    sql := sql + ' AND Id_Document = ' + IntToStr(TDocu.FId_Document);
  if TDocu.FFormat_Code <> '' then
    sql := sql + ' AND Format_Code LIKE '+QuotedStr('%'+TDocu.FFormat_Code+'%');
  if TDocu.FDescription <> '' then
    sql := sql + ' AND Description LIKE '+QuotedStr('%'+TDocu.FDescription+'%');

  if sql <> '' then
  begin
    qryTMP := ConsultaSQL(sql);
    qryTMP.First;
    for i := 0 to qryTMP.RecordCount - 1 do
    begin
      Documents := TDocuments.Create;
      Documents.SetRecord(qryTMP);
      FDocuments.Add(Documents);
      qryTMP.Next;
    end;
    qryTMP.Free;
  end;
end;

function ConsultaSQL(StrSQL: string):TADOQuery;
var
  conBase:TADOConnection;
  qryTMP:TADOQuery;
begin
  conBase := TADOConnection.Create(nil);
  qryTMP := TADOQuery.Create(nil);

  conBase.ConnectionString := 'FILE NAME=' + ExtractFilePath(Application.ExeName) + 'Ozono.udl';
  conBase.Provider := ExtractFilePath(Application.ExeName) + 'Ozono.udl';
  conBase.KeepConnection := True;
  conBase.LoginPrompt := True;
  conBase.Connected := True;

  qryTMP.Connection := conBase;
  qryTMP.Close;
  qryTMP.SQL.Clear;
  qryTMP.SQL.Text := StrSQL;
  qryTMP.Open;
  result := qryTMP;
end;

function EjecutarSQL(StrSQL: string; claDatos:TDatos):TADOQuery;
var
  i: integer;
  qryTMP:TADOQuery;
  conBase:TADOConnection;
begin
  conBase := TADOConnection.Create(nil);
  qryTMP := TADOQuery.Create(nil);

  conBase.ConnectionString := 'FILE NAME=' + ExtractFilePath(Application.ExeName) + 'Ozono.udl';
  conBase.Provider := ExtractFilePath(Application.ExeName) + 'Ozono.udl';
  conBase.KeepConnection := True;
  conBase.LoginPrompt := True;
  conBase.Connected := True;

  qryTMP.Connection := conBase;
  qryTMP.Close;
  qryTMP.SQL.Text := StrSQL;
  
  qryTMP.Parameters.ParseSQL(StrSQL,true);
  for i := 0 to claDatos.Count - 1 do
  begin
    if claDatos[i].Names <> 'PCumple' then
    begin
      qryTMP.Parameters.ParamByName(claDatos[i].Names).Value := claDatos[i].Valor;
      qryTMP.Parameters.ParamByName(claDatos[i].Names).DataType := claDatos[i].Tipos;
    end;
  end;

  qryTMP.ExecSQL;
  result := qryTMP;
end;

end.

Luego a modo de guia les paso la parte que seria la interfaz
Para ello diseño la interfaz serian 3 edit id, format_code, description

Código Delphi [-]
uses Documents;  //use unit

type
  TfrmMain = class(TForm)
  private
    //Declaro mi objeto de tipo Documents MI CLASE
    FDocument:TDocuments;

    function GetDocument: TDocuments;
    procedure SetDocument(const value: TDocuments);

  public
    property Document:TDocuments read GetDocument write SetDocument;
    //Declaro mi objeto de tipo Documents MI CLASE
  end;

implementation

{$R *.dfm}

function TfrmMain.GetDocument: TDocuments;
begin
  if not Assigned (FDocument) then
    FDocument := TDocuments.Create;
  Result := FDocument;
end;

procedure TfrmMain.SetDocument(const value: TDocuments);
begin
  FDocument := value;
end;

//Bueno es un poco mas largo pero para traer los datos y mostrarlos en los edit
//seria algo parecido a esto, aplicando la busqueda, filtrando como se desee

procedure TfrmMain.ApplySearch;
var
  i:integer;
  ListaDocument:TDocumentsList;
begin
  ListaDocument := TDocumentsList.Create;
  ListaDocument.Busqueda(FDocument);

  //para mostrarlo en los edits tendriamos que filtrar de forma tal
  //que la lista devuelta traiga solo 1 fila
  if ListaDocument.Count = 1 then
  begin
    EditId.Text := IntToStr(ListaDocument.Items[0].Id_Document);
    EditFormat_Code.Text := ListaDocument.Items[0].Format_Code;
    EditDescription.Text := ListaDocument.Items[0].Description;
  end;

  //en caso de que se desee mostrar en una listview varios datos
  //seria mas o menos asi
  vieLista.Clear;
  for i := 0 to ListaDocument.Count - 1 do
  begin
    nItem := vieLista.Items.Add;
    nItem.Caption := IntToStr(ListaDocument.Items[i].Id_Document);
    nItem.SubItems.Add(ListaDocument.Items[i].Format_Code);
    nItem.SubItems.Add(ListaDocument.Items[i].Description);
  end;
end;

//Por ahi puede salir algun error porque copie y pegue parte del codigo
//pero es mas o menos para que se tenga una idea

Por ultimo aclaro que lo que quiero es que me ayuden a optimizar mi clase para hacerme la vida mas facil, y adaptar esto para que queden bien definidas, la parte de acceso a datos, logica de negocios, e interface

Entiendo que asi pude separar acceso a datos de la interface, pero creo que me esta faltando un poco para optimizarla aun mas...
bueno desde ya les agradezco la ayuda que puedan darme.

Última edición por elarys fecha: 07-04-2011 a las 15:54:58.
Responder Con Cita
 



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Pasar datos a una clase de un WS gcaffe Internet 1 17-12-2010 16:42:52
clase que contiene otra clase definida de forma posterior astwin OOP 5 20-02-2009 11:26:55
¿¿Es posible pasar una clase como parámetro con el modificador var?? PaFernan99 OOP 3 09-02-2009 18:49:00
Clase jakuna OOP 2 30-08-2007 21:50:35
...la clase... Jure Humor 0 27-07-2004 20:00:47


La franja horaria es GMT +2. Ahora son las 10:00:36.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi