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

Respuesta
 
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
  #2  
Antiguo 07-04-2011
elarys elarys is offline
Miembro
 
Registrado: abr 2007
Posts: 94
Poder: 18
elarys Va por buen camino
Me falto otra clase que tengo para manejar los datos

Código Delphi [-]
unit Base;

interface

uses
  Classes, DB, Variants, SysUtils;

type
  TDato = class(TCollectionItem)
  private
    FNames:String;
    FTipos:TFieldType;
    FValor:Variant;
  public
    property Names: string read FNames write FNames;
    property Tipos: TFieldType read FTipos write FTipos;
    property Valor: Variant  read FValor write FValor;
  end;

  TDatos = class(TCollection)
  private
    function GetItem(Index: integer): TDato;
    procedure SetItem(Index: integer; const Valor: TDato);
  public
    constructor Create; reintroduce; overload;
    procedure AddParam(Names: string; Tipos: TFieldType; Valor: Variant);
    property Items[Index: integer]: TDato read GetItem write SetItem; default;
  end;

implementation

procedure TDatos.AddParam(Names: string; Tipos: TFieldType; Valor: Variant);
var
  claDato:TDato;
begin
  claDato:=TDato.Create(Self);
  claDato.Names := Names;
  claDato.Tipos := Tipos;
  claDato.Valor := Valor;
end;

constructor TDatos.Create;
begin
  inherited Create(TDato);
end;

function TDatos.GetItem(Index: integer): TDato;
begin
  Result := TDato(inherited GetItem(Index));
end;

procedure TDatos.SetItem(Index: integer; const Valor: TDato);
begin
  inherited SetItem(Index, Valor);
end;

end.
Responder Con Cita
  #3  
Antiguo 07-04-2011
Avatar de gatosoft
[gatosoft] gatosoft is offline
Miembro Premium
 
Registrado: may 2003
Ubicación: Bogotá, Colombia
Posts: 833
Poder: 21
gatosoft Va camino a la fama
Amigo elarys, te doy un par de sugerencias, sin ser experto en el tema de capas...

** Te recomiendo utilizar TClientDataset. Esta es una herramienta muy poderosa que te sirve como interface entre tus componentes de "la capa de datos" y las demás capas. Sin importar que componentes de acceso a datos estes utilizando: ADO, ZEOS, dbexpress, etc.

De esta manera tu codigo en las capas superiores no lo tendras que tocar cuando quieras cambiar de base de datos... Es decir, podrías pensar a futuro, en "enchufar" tu aplicación a una base de datos y no en "migrar" de motor. (Obivamente todo tiene sus limites y excepciones)

** Te recomiendo utilizar los componentes dbExpress, aunque cada uno tiene sus gustos y preferencias, pero por mi parte pienso que tienen como ventaja principal, que son componentes nativos de Delphi, y que junto al TClientDataset Embarcadero le esta trabajando bastante orientandolos por a la tecnología DataSnap.

** Utiliza la ventaja del polimorfismo que te brinda la POO. Puedes redefinir tus métodos independiente del comoponete de acceso a datos que utilices. Por ejemplo, hasta donde veo, podrias reemplazar todos tus TADOQuery por TDataset o en últimas por un TClientDatset (que tambien podría tomarse como genérico). Por ejemplo

Código Delphi [-]
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;

deberia quedar:

Código Delphi [-]
procedure TDocuments.SetRecord(qryTMP:TDataset);
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;

de esta manera cuando migres puedes llamar esta funcion pasando un componente ADO, Zeos, o dbExpress


** Las funciones ConsultarSQL y EjecutarSQL no deberían compartir unidad con tus clases principales (Tdocuments y TDocumentsList), estas debrían estar en un Datamodule y ademas no deberían ser globales, sino que deberían ser parte del propio Datamodule.

** No veo necesario que tus funciones EjecutarSQL y ConsultarSQL deban conectarse cada vez que las requieras... podrías mantener una conexión activa de forma permanente y pasarla como parámetro a tus dos funciones. Tambien es útil si manejas varias bases de datos:

Código Delphi [-]
function EjecutarSQL(conn: TSqlConnection; StrSQL: string; claDatos:TDatos):TDataset;

El componente TSqlConnection hace parte de dbexpress, pero puedes utilizar cualquiera, como te dije con estos componentes puedes trabajar varias bases de datos como SQL Server, MySQL, PostgreSQL, DB2, ORACLE... entre otras.

** En cuanto a tus clase principales (TDocuments y TDocumentsList), te recomiendo "liberarlas" de sentencias SQL. y pasar finalmente todo este codigo a un datamodule, haciendo llamadas a procedimeintos.

Código Delphi [-]
procedure TDocuments.SaveModified;
begin
  SetParameter;
  ElDataModule.ActualizarDocuento(claDatos);
end;

En el caso de tu funcion búesqueda

Código Delphi [-]
procedure TDocumentsList.Busqueda(TDocu:TDocuments);
var
  Documents:TDocuments;
begin
  if not assigned (TDocu) then
    TDocu := TDocuments.Create;

  ElDatamodule.RealizarBusqueda(TDocu, qryTMP); // Aqui haces todo lo relacionado 
                                                // al SQL o al motor de base de datos
                               
  while not qryTMP.Eof do
  begin
    Documents := TDocuments.Create;
    Documents.SetRecord(qryTMP);
    FDocuments.Add(Documents);    
    qryTMP.Next;
  end;//while  
end;

De esta manera independizas (un poco) la logica de negocio de la forma como buscas... es decir, el dia de mañana en lugar de realizar la busqueda via SQL, podrias utilizar un porcedimiento almacenado, o cualquier otra funcionalidad que tu motor escogido te ofrezca. y no tendrias por que tocar la logica que plantea tu clase...


Finalmente, el Datamodule será el componente duro, pues alli estarán "las tripas" de la aplicación... es alli donde sabras como te conectas a tu BD.

espero que te sirva,

un saludo,
Responder Con Cita
Respuesta



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 06:00:55.


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